Reputation: 2470
I'm using this code for replacing space with / in one of my fields.
$('#field').bind('keyup keypress blur', function()
{
var myStr = $(this).val()
myStr=myStr.replace(/\s+/g, "/");
$('#field').val(myStr);
});
How can I add 2 spaces around "/"?
If I try to use .replace(/\s+/g, " / ");
it gives me this / / / / / / / r
as i type.
Upvotes: 1
Views: 575
Reputation: 5119
Try this:
$('#field').bind('keyup', function() {
var myStr = $(this).val()
myStr=myStr.replace(/\s+$/g, ' / ');
$('#field').val(myStr);
});
https://jsfiddle.net/uo62y4ja/3/
Added $
to the regex and added spaces around /
in replace value. Also, reduced the key events to just keyup
.
EDIT:
anubhava is right about using keypress
instead of keyup
. Main difference is then adding the $
in the regex.
Upvotes: 1
Reputation: 784898
You shouldn't include keyup
event otherwise replaced space also gets replaced by " / "
repeatedly.
Following should work:
$('#field').bind('keypress', function() {
var myStr = $(this).val()
myStr=myStr.replace(/\s+/g, " / ");
$('#field').val(myStr);
});
Upvotes: 1