tags:

views:

214

answers:

2

Hi I have this code, I want it to remove all the double spaces from a text area, but it will only remove the first occurrence each time.

$(document).ready(function(){
  $("#article").blur(function(){
    ///alert($(this).val());
    $(this).val($(this).val().replace(/\s\s+/, ' '));
  });
});

I've also tried removeAll(), but it won't work at all. any help would be great, thanks. I have a live example online at http://jsbin.com/ogasu/2/edit

+3  A: 
.replace(/\s\s+/g, ' '));

note the g

mkoryak
+4  A: 

Use the g modifier in your regular expression to match and replace globally:

/\s\s+/g

Otherwise only the first match will be replaced.

By the way, as of jQuery 1.4 and later you can also provide val a function that performs the replacement:

$(this).val(function(index, value) {
    return value.replace(/\s\s+/g, ' ');
});

That will save you a second call of $(this).val.

Gumbo