Max
Max

Reputation: 4408

Replacing consecutive whitespace with one whitespace character

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).

Upvotes: 3

Views: 3081

Answers (3)

deviousdodo
deviousdodo

Reputation: 9172

You can do both at once with:

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

Upvotes: 3

Davide
Davide

Reputation: 2339

For spaces:

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

For tabs:

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

Upvotes: 1

davin
davin

Reputation: 45555

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

returns

" this is tooo spaced "

Upvotes: 4

Related Questions