wyc
wyc

Reputation: 55263

How to add a condition to the following replace?

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)

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.

Upvotes: 0

Views: 378

Answers (2)

thatguymatt
thatguymatt

Reputation: 11

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.

Upvotes: 1

anubhava
anubhava

Reputation: 784918

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, '“$1”').replace(/"/g, '“');

console.log(result)

Upvotes: 1

Related Questions