Reputation: 55273
The following code replace straight double quotes with curly double quotes:
const input = `"Line 1"
"Line 2
"Line 3"
Line 4`
const output = input.replace(/\"(.*?)(\")/g, '“$1”')
console.log(output)
There's a problem, though. Sometimes a line doesn't have a closing double quote (which indicates that the quotes continues on the line below). So the opening double quote won't be replaced:
`“Line 1$1”
"Line 2
“Line 3$1”
Line 4`
How to modify the regex so it also replaces opening double quotes that aren't followed by a closing double quote?
Desired output:
`“Line 1$1”
“Line 2
“Line 3$1”
Line 4`
Upvotes: 2
Views: 99
Reputation: 626758
You can use
.replace(/^"([^"\n\r]*)"?$/gm, "“$1”")
See the regex demo. The regex matches all non-overlapping occurrences (g
), while matching start of lines with ^
and end of lines with $
(due to m
) and means
^
- start of a line"
- a double quotation mark([^"\n\r]*)
- Group 1: any zero or more chars other than "
, CR and LF"?
- an optional "
char$
- end of any line.See the JavaScript demo:
const input = `"Line 1"
"Line 2
"Line 3"
Line 4`
const output = input.replace(/^"([^"\n\r]*)"?$/gm, '“$1”')
console.log(output)
Upvotes: 1
Reputation: 637
const input = `"Line 1"
"Line 2
"Line 3"
Line 4`
const output = input.replace(/"([^"/]*)"/g, '“$1”')
console.log(output)
Upvotes: 1
Reputation: 179
I would go in 2 successive replace()
, if it's ok:
"...'"
form"...
const output = input
.replace(/\"(.*?)(\")/g, '“$1”')
.replace(/\"(.*)/g, '“$1”')
But I didn't understand if you wanted to match multilines results in an unique final string, or just add quotes to the end of each line
Upvotes: 1