1

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

2
  • 2
    Have you tried: string.replace(/;+/g, ',');? Commented Jan 8, 2016 at 0:45
  • Yep, it was the + quantifier I missed, thank. I knew that at a time... ;) Commented Jan 8, 2016 at 0:49

2 Answers 2

2

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, ',');
Sign up to request clarification or add additional context in comments.

Comments

2

This should do the trick:

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

It just replaces all group of semicolons together for a comma

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.