The following code is replacing opening and closing straight double quotes by opening and closing curly double quotes:
const string = `Not dialogue not dialogue.
"Dialogue dialogue.
"Dialogue dialogue."
"Dialogue," not dialogue. "Dialogue."`
const result = string.replace(/"([^"\n\r]*)"/g, '“$1”')
console.log(result)
How to modify this code so the opening straight double quote in "Dialogue dialogue (second line) is also replaced by an opening curly double quote (without adding a closing curly double quote at the end of the line)?
Desired output:
Not dialogue not dialogue.
“Dialogue dialogue.
“Dialogue dialogue.”
“Dialogue,” not dialogue. “Dialogue.”
CodePudding user response:
You can use
const string = `Not dialogue not dialogue.
"Dialogue dialogue.
"Dialogue dialogue."
"Dialogue," not dialogue. "Dialogue."`
const result = string.replace(/"([^"\n\r]*)("|$)/gm, (x,y,z) => z == '"' ? `“${y}”` : `“${y}`)
console.log(result)
Details:
"- a double quote([^"\n\r]*)- Group 1: any zero or more chars other than", CR and LF("|$)- Group 2:"or end of a line (mmakes$match the end of any line).
The (x,y,z) => z == '"' ? `“${y}”` : `“${y}` replacement replaces with “ Group 1 value ” if Group 2 value is ", else, the replacement is “ Group 1 value.
