Passing string variable with spaces

Tags: , , , ,



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.

Answer

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

So use the following code-

<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>


Source: stackoverflow