-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!

0

2 Answers 2

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

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

Comments

2

Regular expressions are your friend!

str = str.replace(/ +/g, " ");

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.