0

var s = "Hello! I'm billy! what's up?"; var result = s.split(" ").join(); console.log(result);

Got this result

Hello!,I'm,,billy!,what's,,,,up? 

How can i get rid of this annoying extra spaces between string? So it might look like this.

Hello!,I'm,billy!,what's,up? 

4 Answers 4

1

Use a regular expression to find all the spaces throughout the string and rejoin with a single space:

var s = "Hello! I'm billy! what's up?"; var result = s.split(/\s+/).join(" "); console.log(result);

You can also do this without using .split() to return a new array and just use the String.replace() method. The regular expression changes just a little in that case:

var s = "Hello! I'm billy! what's up?"; var result = s.replace(/ +/g, " "); console.log(result);

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

4 Comments

@RoelDelosReyes You're welcome. Don't forget to up vote and mark as the answer.
if space is at end of string?
@JayShankarGupta not needed i can do it with just trim() but man it is quite annoying with extra spaces between strings
@JayShankarGupta What if the space is at the end? The regular expression used finds all extra space no matter where it is.
1

You want replace and \s+

\s+ Matches multiple white space character, including space, tab, form feed, line feed.

trim to remove extra white space at the start and end of the string

var s = " Hello! I'm billy! what's up? "; console.log(s.replace(/\s+/g, " ").trim());

Comments

0

var s = "Hello! I'm billy! what's up?"; var result = s.replace(/\s+/g,' ').trim(); console.log(result);

Comments

0

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

var str = "Hello! I'm billy! what's up?"; str = str.replace(/ +/g, " "); console.log(str); var strr = "Hello! I'm billy! what's up?"; strr = strr.replace(/ +/g, " "); console.log(strr);

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.