-2

Good day everyone,

I have a text area that takes user input (duh!) and I want to eliminate excess spaces.

Example

The string:

The(s)(s)(s)quick(s)brown(s)(s)fox(s)(s)(s)jumped(s)over(s)the(s)lazy(s)(s)dog!

Should be:

The(s)quick(s)brown(s)fox(s)jumped(s)over(s)the(s)lazy(s)dog!

(s) = space

I am aware of the trim() function in JavaScript to eliminate spaces at both ends (beginning and the end of string), but how do I do that between words and without fully eliminating all spaces? Just stacking them to one space if that makes it easier to understand :)

Thanks in advance!

Community
  • 1
  • 1
Jomar Sevillejo
  • 1,648
  • 2
  • 21
  • 33

2 Answers2

4

You could use a regex (/ +/g, " "):

var str = "The   quick brown  fox   jumped over the lazy  dog!";
str = str.replace(/ +/g, " "); 
// Results in "The quick brown fox jumped over the lazy dog!"

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
2

Regular expressions are your friend!

str = str.replace(/ +/g, " ");
Dev Chakraborty
  • 303
  • 2
  • 10