3

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. 
0

4 Answers 4

5

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, ' ')
);

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

Comments

1

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.

Comments

1

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());

Comments

1

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, ' '));

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.