Skip to content
Advertisement

Passing string variable with spaces

In the following code:

    <script type="text/javascript">
        function updateView(set) {
            $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
                $( "#content" ).html( data );
            });
        }
    </script>

‘set’ is a string variable which can have spaces in it. I’m noticing when it has spaces it’s not working correctly. How can I fix this?

EDIT: For clarity, I’d like to keep the spaces intact.

Advertisement

Answer

You have to replace intermediate space (' ') with '%20' using replace(), and eliminate boundary spaces (' ') using trim():

<script type="text/javascript">
    function updateView(set) {
    set=set.trim().replace(/ /g, '%20');
        $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
            $( "#content" ).html( data );
        });
    }
</script>
Advertisement