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.
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.
Share Improve this question edited Oct 14, 2013 at 4:27 Howard asked Oct 14, 2013 at 4:03 HowardHoward 3,75815 gold badges64 silver badges87 bronze badges 4- I'd like to pass the string while keeping the spaces. – Howard Commented Oct 14, 2013 at 4:32
- It doesn't have to be in the URL, I'm just trying to keep the data intact as it is. – Howard Commented Oct 14, 2013 at 4: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 Commented Oct 14, 2013 at 4: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 Commented Oct 14, 2013 at 4:41
3 Answers
Reset to default 8NOTE: 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,"+")},
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>
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