views:

1306

answers:

8

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

+12  A: 
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,' ');
watain
Funny your test string doesn't even have two spaces in it.
Josh Stodola
Too bad, forgot those hehe ;)
watain
just realized you already had what i recently came up with, +1 :)
meder
For some reason this isn't working... A lot of "  " are showing up... Likely due to CKEDITOR...
AnApprentice
K turns out JQUERY's text() was messing things up. fixed - thanks all!
AnApprentice
+2  A: 

Just replace \s{2,} with ' '. Something like:

string = string.replace(/\s{2,}/g, ' ');
BalusC
Technically not as efficient as it could be, since you'll replace things that don't need replacing. For example, the spaces in `"This is a sentence."` will match 3 times and get replaced with a single space, even though you don't need to do any work here.
John Feminella
Good point. Improved it.
BalusC
Does this also remove, whitespacy tab characters?
AnApprentice
You also need to add 'g' flag to the regex.
Rafael
@nobosh: yes, it replaces all white-space characters (space, tab, \r, \n, \v \f) with space-character.
Rafael
@nobosh: yes it takes tabs into account as well, as opposed to `/ {2,}/`. @rafael: hmm I wish there was a `replaceAll` in Javascript as in Java. Fixed.
BalusC
+8  A: 

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+/, '') )
meder
The first one is totally pointless, \s\s+ means, an \s followed by one or more \s+, which can be reduced to a single \s+, the second example is more accurate because we only want to replace double spaces, not newlines, the third is more optimized because it only applies to examples with 2+ spaces. But str.replace(/ +(?= )/g,'');, only applies to examples with 2+ spaces but saves overwriting a space with a space step.
Evan Carroll
EvanCarroll you **fail** because \s\s+ is definitely different to \s+. \s\s+ would match '\t\t' or '\t\t\t' but NOT '\t'. And that's what it's all about, you don't want replace every f-en single whitespace character.
watain
A: 
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, " ");
Brian Campbell
using + seems cleaner but it will also replace single spaces with single spaces, a little bit redundant and I'm not sure but it may create performace problems with a much longer text.
marvin
I tend to use the shortest, simplest solution that will work, and only worry about that sort of optimization if I know that I need to be matching against a very large string, an at that point I will actually measure different solutions to see which will be faster. It can be hard to predict in advance what will be fastest without testing; for instance, in JavaScript interpreters, some complicated regular expressions will cause you to switch from a fast JIT compiled implementation to a slow interpreted one.
Brian Campbell
+1  A: 

Also a possibility:

str.replace( /\s+/g, ' ' )
thenduks
A: 
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');
marvin
+4  A: 

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

Edward Loper
well done sir.....
AnApprentice
A: 

A good solution is given in http://thedailywtf.com/Articles/A-Spacy-Problem.aspx

an0nym0usc0ward