Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':
string = string.replace(/\s\s+/g, ' ');
If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:
string = string.replace(/ +/g, ' ');
Answer from BalusC on Stack OverflowGiven that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':
string = string.replace(/\s\s+/g, ' ');
If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:
string = string.replace(/ +/g, ' ');
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.)
At first I thought this task won’t take more than half hour for me as the code was converting the dataframe into a temporary view and using sql on it. But the problem arose when I started testing and the escaping character was also eliminated then the special spaces like \n, \t started eliminating.
My task is to replicate just was oracle replaces that is just the multiple spaces with single space excluding all the escape characters and or the special spaces.
Can someone please help me on this. It will work if you suggest any sql regex replace or even any pyspark, pandas code to get it done as I am performing it in Databricks.
Thanks in advance🤗
removed random amount of extra spaces from string
java - Regex or way to replace multiple space with single space - Stack Overflow
RegEx how to replace multiple spaces with a single one
How can I use regex on multiple spaces?
To replace multiple spaces
output = input.replaceAll("[ ]+", " ");
Or replace multiple whitespace characters (including space, tab, new line, etc.)
output = input.replaceAll("\\s+", " ");
This is a variation of @p.s.w.g - it ignores newlines, but still get tabs and such.
output = input.replaceAll("[^\\S\\r\\n]+", " ");