scubasteve
scubasteve

Reputation: 2858

RegEx to replace variable quantity of characters with single character

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

Upvotes: 1

Views: 77

Answers (2)

Jezzamon
Jezzamon

Reputation: 1491

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, ',');

Upvotes: 2

Alex Santos
Alex Santos

Reputation: 2950

This should do the trick:

d.replace(/[;]+/g, ',')

It just replaces all group of semicolons together for a comma

Upvotes: 2

Related Questions