Home > Back-end >  Regex to match quotation marks
Regex to match quotation marks

Time:11-12

I'm trying to replace beginning and ending quotation marks with the correct local (swiss) type of quotation marks with regex/javascript.

this "example": this «example»
this “example”: this «example»
this ‘example’: this ‹example›

Any help appreciated

What I have so far is a four step replacement:

replace(/["“”„](\w)/g, '«$1')
replace(/(\w)["“”„]/g, '$1»')
replace(/[‘’](\w)/g, '‹$1')
replace(/(\w)[‘’]/g, '$1›')

The issue with this regex: a single apostroph is getting replaced as well: that’s: that›s I would prefer to replace the opening and closing quotes in one step.

CodePudding user response:

A regex will not be fool-proof. You are probably going to have to tokenize the string and parse it.

Note: When nesting quotes, multiple occurrences of the same quote character will not be converted.

const fixQuotes = (str) =>
  str
    .replace(/["](. )["]/g, '«$1»')
    .replace(/[“](. )[”]/g, '«$1»')
    .replace(/['](. )[']/g, '‹$1›')
    .replace(/[‘](. )[’]/g, '‹$1›');

console.log('CORRECT');
console.log(fixQuotes(`Text: "example", “example”, ‘example’`));
console.log(fixQuotes(`Text: “nested ‘example’”`));
console.log(fixQuotes(`Text: "nested 'example'"`));

console.log('INCORRECT');
console.log(fixQuotes(`Text: "nested "example""`));
console.log(fixQuotes(`Text: “nested “example””`));
.as-console-wrapper { top: 0; max-height: 100% !important; }

You would essentially have to convert twice:

console.log(fixQuotes(fixQuotes(`Text: "nested "example""`)));
console.log(fixQuotes(fixQuotes(`Text: “nested “example””`)));
  • Related