Reputation: 55263
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
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
Reputation: 784918
You may use this code with 2 .replace
method calls:
.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