3

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

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

note the g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.