0

So i have a dubt

if for example i have:

var string = "The     String";

but i want string always to look "The String" (only 1 blank space in case of multiple sequenze of them)

how to do that in a clever way and dynamically, i mean there are many cases like these:

string = "This        String";

string = "This String    is           short";

string = "This is    the   string";

i'm totally dumb in regexp (not only on it) and i guess it is the only way uh?

itsme
  • 48,972
  • 96
  • 224
  • 345

1 Answers1

2

You should use a regex to get all spaces and replace it with one

string.replace(/\s\s+/g, " ");

If you only want it to work on a space and not tabs, use this:

string.replace(/  +/g, " ");

In the regex world "+" means 1 and any more that follow it. The "g" at the end means "global", or do it more than once. Removing the g would replace the first string of spaces but not any others. "\s" means all space-type characters which includes " " and tabs.

DemiImp
  • 968
  • 8
  • 18
  • 2
    not worth answering. Your answer is in the duplicate I posted – mplungjan Apr 18 '14 at 16:03
  • @Demilmp should i go for your solution or http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space solution? why does? – itsme Apr 18 '14 at 16:33
  • @sbaaaang In most cases it doesn't matter. If you look at the second answer to the link you posted, someone benchmarked the queries in FireFox. I updated my answer to have 2 "\s" and 2 " ", which appears to be twice as efficient. If you go with what I changed it to, you should get optimal speeds (or very close to it). – DemiImp May 13 '14 at 17:51