Given a string like:
\"The dog has a long tail, and it is RED!\"
What kind of jQuery or JavaScript magic can be used to keep spaces to only o
var text = `xxx df dfvdfv df
dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');
result:
"xxx df dfvdfv df dfv"
Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:
str.replace( / +/g, ' ' ) -> 380ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( / +/g, ' ' ) -> 790ms
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.)
var myregexp = new RegExp(/ {2,}/g);
str = str.replace(myregexp,' ');
Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)
var str="The dog has a long tail, and it is RED!";
var rule=/\s{1,}/g;
str = str.split(rule).join(" ");
document.write(str);
We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.
Add the text into some file say test
manjeet-laptop:Desktop manjeet$ cat test
"The dog has a long tail, and it is RED!"
We can use the following regex to replace all white spaces with single space
manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"
Hope this serves the purpose
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,' ');