Reputation: 114
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
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:
You can combine modifiers, such as g and i together, to get a global case insensitive search.
Upvotes: 1
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
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
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