Shift 'n Tab
Shift 'n Tab

Reputation: 9443

Remove multiple white space between text

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

Answers (4)

suraj.tripathi
suraj.tripathi

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

L Y E S  -  C H I O U K H
L Y E S - C H I O U K H

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

Scott Marcus
Scott Marcus

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

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

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

Upvotes: 0

Related Questions