Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top