Given a string like:
"The dog has a long tail, and it is RED!"
What kind of JQUERY, JavaScript magic can be used to keep spaces to only 1 max?
Goal:
"The dog has a long tail, and it is RED!"
thanks
Given a string like:
"The dog has a long tail, and it is RED!"
What kind of JQUERY, JavaScript magic can be used to keep spaces to only 1 max?
Goal:
"The dog has a long tail, and it is RED!"
thanks
var str = "The dog has a long tail, and it is RED!";
str = str.replace(/ {2,}/g,' ');
EDIT: If you wish to replace all kind of whitespace characters the most efficient way would be like that:
str = str.replace(/\s{2,}/g,' ');
Just replace \s{2,}
with ' '
. Something like:
string = string.replace(/\s{2,}/g, ' ');
This is one solution, though it will target all space characters:
"The dog has a long tail, and it is RED!".replace(/\s\s+/g, ' ')
"The dog has a long tail, and it is RED!"
Edit: This is probably better since it targets a space followed by 1 or more spaces:
"The dog has a long tail, and it is RED!".replace(/ +/g, ' ')
"The dog has a long tail, and it is RED!"
Alternative method:
"The dog has a long tail, and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"
I didn't use /\s+/
by itself since that replaces spaces that span 1 character multiple times and might be less efficient since it targets more than necessary.
I didn't deeply test any of these so lmk if there are bugs.
Also, if you're going to do string replacement remember to re-assign the variable/property to its own replacement, eg:
var string = 'foo'
string = string.replace('foo', '')
Using jQuery.prototype.text:
var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )
var string = "The dog has a long tail, and it is RED!";
var replaced = string.replace(/ +/g, " ");
Or if you also want to replace tabs:
var replaced = string.replace(/\s+/g, " ");
Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +/g, ' ' ) -> 380ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / +(?= )/g, ' ') -> 3250ms
This is on Firefox, running 100k string replacements.
I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.
(Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)
A good solution is given in http://thedailywtf.com/Articles/A-Spacy-Problem.aspx