Alex Rivera | Logout

Regex to replace multiple spaces with a single space

Asked 2009-12-30T17:28:58.513
805

Given a string like:

"The dog      has a long   tail, and it     is RED!"

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

Goal:

"The dog has a long tail, and it is RED!"
Edit
Report

3 Answers

13

Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)

var str="The dog      has a long   tail, and it     is RED!";
var rule=/\s{1,}/g;

str = str.split(rule).join(" "); 

document.write(str);

answered 2013-03-15T05:10:50.947
10

More robust:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}
answered 2011-05-10T15:37:00.480
3
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

Or if you also want to replace tabs:

var replaced = string.replace(/\s+/g, " ");
answered 2009-12-30T17:32:50.517

Your Answer