Home > other >  How to add a condition to the following replace?
How to add a condition to the following replace?

Time:11-18

I want to replace all straight double quotes with curly double quotes:

const text = `"This has an opening and a closing quote."

"This only has an opening quotes

This doesn't have quotes.`

const result = text.replace(/"([^"\n\r]*)"?/g, '“$1”')

console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The problem with my current .replace is that it's adding curly double quotes when there aren't closing straight double quotes:

“This has an opening and a closing quote.”

“This only has an opening quotes”

This doesn't have quotes.

How to change my .replace function so it doesn't add curly double closing quotes when there are no straight double closing quotes?

Expected output:

“This has an opening and a closing quote.”

“This only has an opening quotes

This doesn't have quotes.

CodePudding user response:

You may use this code with 2 .replace method calls:

  1. First we match pair of straight quotes and replace with curly double quotes (html entities).
  2. In second .replace we just match single " and replace with left curly double quote (html entities).

This assumes that single " after quoted pair replacement are opening ones.

Code:

const text = `"This has an opening and a closing quote."

"This only has an opening quotes

This doesn't have quotes.`;

const result = text.replace(/"([^"\n\r]*)"/g, '&ldquo;$1&rdquo;').replace(/"/g, '&ldquo;');

console.log(result)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use Unicode rather than the HTML entities. Like so:

const text = `"This has an opening and a closing quote."

"This only has an opening quotes

This doesn't have quotes.`

const result = text.replace(/"([^"\n\r]*)"?/g, '\u201d$1\u201c')

console.log(result)

Where \u201d is the opening curly quotes and \u201c is the closing curly quotes.

  • Related