Phoenix
Phoenix

Reputation: 114

How to trim spaces between word, and after comma using javascript

I have following string called name and I want to trim spaces between words in a sentence and to trim space after comma also. I am able to trim extra spaces using trim() at the begining and end of the sentence.
[I am using javascript to implement my code]

name = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.  

Expected Output:

name = ' Barack Hussein  Obama II is an American politician who served  as the 44th President of the United States from January 20, 2009, to January 20, 2017. 

Upvotes: 3

Views: 457

Answers (4)

Debashis Sahoo
Debashis Sahoo

Reputation: 5922

By default string.replace in JavaScript will only replace the first matching value it finds, adding the /g will mean that all of the matching values are replaced.

The g regular expression modifier (called the global modifier) basically says to the engine not to stop parsing the string after the first match.

var string = "      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017."
alert(string)
string = string.replace(/ +/g, ' ');
alert(string)

A list of useful modifiers:

  • g - Global replace. Replace all instances of the matched string in the provided text.
  • i - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
  • m - Multi-line replace. The regular expression should be tested for matches over multiple lines.

You can combine modifiers, such as g and i together, to get a global case insensitive search.

Upvotes: 1

Ewomazino Ukah
Ewomazino Ukah

Reputation: 2366

let msg = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.';

console.log(msg.replace(/\s\s+/g, ' '));

Upvotes: 1

Mat.Now
Mat.Now

Reputation: 1725

In angularjs you can use trim() function

const nameStr = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.';

console.log(nameStr.replace(/\s+/g, ' ').trim());

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370779

Assuming that the remaining double-spaces are just a typo, you can use a regular expression to match one or more spaces, and replace each with a single space:

const name1 = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.';
console.log(
  name1.replace(/ +/g, ' ')
);

Upvotes: 5

Related Questions