Reputation: 2975
How can I make extra space be removed in a string in Javascript ?
For example
I have a string the following string
var string ="how are you today";
I would like to know what function or trick I could use to dynamically remove extra space in strings in Javascript so that I can have var string ="how are you today";
instead ..
How could I do this ?
Upvotes: 2
Views: 2579
Reputation: 6937
Lets assume you have
var myString ="how are you today";
If you just want to handle spaces:
myString.replace(/ +/g, ' ');
If you want to replace tabs and new lines as well:
myString.replace(/\s+/g, ' ');
Please note that this does not change the value of myString, but rather return a new string with the spaces removed. So to save this result you would do, for example:
var fixedString = myString.replace(/ +/g, ' ');
Upvotes: 6