Reputation: 9443
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?
Upvotes: 0
Views: 48
Reputation: 467
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());
Upvotes: 1
Reputation: 5080
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);
Upvotes: 0
Reputation: 65808
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);
Upvotes: 1
Reputation: 6088
var s = "Hello! I'm billy! what's up?";
var result = s.replace(/\s+/g,' ').trim();
console.log(result);
Upvotes: 0