Ad

RegEx To Replace Variable Quantity Of Characters With Single Character

- 1 answer

Given this string

var d = 'The;Quick;;Brown;Fox;;;;;;Jumps';

What RegEx would I need to convert to this string:

'The,Quick,Brown,Fox,Jumps'

I need to replace 1-n characters (e.g. ';') with a single character (e.g. ',').

And because I know that sometimes you like to know "what are you trying to accomplish??" I need to condition a string list of values that can be separated with a combination of different methods:

'The ,     Quick \r\n Brown  , \r\n Fox    ,Jumps,'

My approach was to convert all known delimiters to a standard character (e..g ';') and then replace that with the final desired ', ' delimiter

Ad

Answer

as Josh Crozier says, you can use

d = d.replace(/;+/g, ',');

You can also to the whole thing in one operation with something like

d = d.replace(/[,; \r\n]+/g, ',');

The [,; \r\n]+ part will find groups that are made of commas, semicolons, spaces etc.. Then the replace will replace them all with a single comma. You can add any other characters you want to treat as delimiters in with the brackets.

EDIT: actually, it's probably better to use something like this. The \s will match any whitespace character.

d.replace(/[,;\s]+/g, ',');
Ad
source: stackoverflow.com
Ad