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

  • A+
Category:Languages

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.  

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: