regex - javascript replace all occurrences ",\S" with ", \S" -
i want have spaces separating items in csv string. "123,456,789" => "123, 456, 789". have tried, been unable construct regexp this. read postings , thought trick, no dice.
 text = text.replace(new regexp(",\s", "g"), ", "); could show me doing wrong?
you have 2 problems:
- backslashes pain in the, um, backslash; because have many meanings (e.g. let put quote-mark inside string), end needing escape backslash backslash, need ",\\s"instead of",\s".
- the \smatches a character other whitespace, character gets removed , replaced along comma. easiest way deal "capture" (by putting in parentheses), , put in again in replacement (with$1).
so end this:
text = text.replace(new regexp(',(\\s)', "g"), ", $1"); however, there neater way of writing this, because javascript lets write regex without having string, putting between slashes. conveniently, doesn't need backslash escaped, shorter version works well:
text = text.replace(/,(\s)/g, ", $1"); as alternative capturing, can use "zero-width lookahead", in situation means "this bit has in string, don't count part of match i'm replacing". that, use (?=something); in case, it's \s want "look ahead to", (?=\s), giving version:
text = text.replace(/,(?=\s)/g, ", "); 
Comments
Post a Comment