3

I want to replace two or more occurrences of whitespace with just one whitespace character using JavaScript (this code is going to sit inside a chrome extension).

3 Answers 3

4
" this is tooo spaced ".replace(/\s+/g, " "); 

returns

" this is tooo spaced " 
Sign up to request clarification or add additional context in comments.

1 Comment

This matches one or more. The OP was looking for "more than one". /\s{2,}/g would make more sense (though yours still works).
3

You can do both at once with:

"str str\t\t\tstr".replace(/(\s)+/g, "$1"); 

3 Comments

Didn't know that \s matched \t as well. Impressive!
@Davide how would I go about replacing tabs with space now? do I do an other loop?
If you want all white space characters replaced by a space, you should simply use what davin wrote. I added my example because I thought you wanted multiple tabs to be replaced by a tab, multiple spaces by a space, etc.
1

For spaces:

'test with spaces'.replace( /\s+/g, ' ' ); 

For tabs:

'test\t\t\twith\t\t\ttabs'.replace( /\t+/g, '\t' ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.