Sufhal
Sufhal

Reputation: 11

Regex select specific characters between double quotes

I would like to extract specific character i.e. ; that are located between quotes (") with a Regex expression.


String example :

Lorem;ipsum;"dolor;sit;";amet;


Should select every ; in quotes :

Lorem;ipsum;"dolor;sit;";amet;


I tried this one but it doesn't work

(?<=\")(;)*(?=\")

Any idea ? Thank you in advance

Upvotes: 1

Views: 675

Answers (1)

Apolo
Apolo

Reputation: 4050

You will have to do it in two steps:

  1. select every parts between quotes: /"[^"]+"/gm
  2. in these matchs, search for ;

you should be able to use String.prototype.replace with the given regex and look for ";" in your replace callback.

here is a demo:

function escapeCsvDelimiter(input) {
  return input.replace(/"[^"]+"/gm, (match) => match.replace(/;/g, '\\;'));
}

const test = 'Lorem;ipsum;"dolor;sit;";amet;"jhv;"';
const result = escapeCsvDelimiter(test);

console.log(result);

Upvotes: 1

Related Questions