5

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.

Howard
  • 3,648
  • 13
  • 58
  • 86
  • I'd like to pass the string while keeping the spaces. – Howard Oct 14 '13 at 04:32
  • It doesn't have to be in the URL, I'm just trying to keep the data intact as it is. – Howard Oct 14 '13 at 04:34
  • As you say, I think you should replace the spaces as I have answered and replace all occurrences of the new character with spaces before any other operation with the data, to get the data intact. – Rajesh Paul Oct 14 '13 at 04:38
  • As the URL doesn't support spaces and what you want is much similar to that of URL formatting you should try it. – Rajesh Paul Oct 14 '13 at 04:41

3 Answers3

8

NOTE: that $.trim() is now deprecated for .trim()

Use set.trim() to remove leading or trailing spaces and either

set.replace(/ /g,"+")  

or

encodeURI(set)

to keep the spaces inside the string
(refer When are you supposed to use escape instead of encodeURI / encodeURIComponent?)

To do both in one go just chain them

set.trim().replace(/ /g,"+")

Note you may use %20 instead of the plus if you prefer.

But is it not a parameter? If so, perhaps you want to pass it as

$.post("<?php echo base_url("/show_cards/load_page")."/"; ?>",
  {"set":set.trim().replace(/ /g,"+")},
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    This is the only answer that answers this question in both parts. It's not about removing or trimming those spaces only. – Hanky Panky Oct 14 '13 at 04:17
4

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>
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Rajesh Paul
  • 6,793
  • 6
  • 40
  • 57
2

use Trim

<script type="text/javascript">
        function updateView(set) {
          var set=$.trim(set);// by this  leading or trailing spaces removes  
            $.post("<?php echo base_url("/show_cards/load_page")."/"; ?>"+set, function( data ) {
                $( "#content" ).html( data );
            });
        }
    </script>

you can also use string.replace

  var set=  set.replace(/ /g,"+") ;// like that way in this all the spaces removes
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55