kirqe
kirqe

Reputation: 2470

How to replace space character with slash surrounded by spaces " / "?

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

Answers (2)

lintmouse
lintmouse

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

anubhava
anubhava

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); 
});

JSFiddle Demo

Upvotes: 1

Related Questions