This code turns straight single quotes into curly single quotes:
var result = 'This \'is an\' example'.replace(/(?<!\w)\'\S(.*?)\S\'(?!\w)/g, '‘$1’')
alert(result)
I thought the output would be:
This ‘is an’ example
But the output was this:
This ‘s a’ example
I'm not sure why the bounding characters inside the quotes are being removed.
Why is this and how to fix it?
https://jsfiddle.net/gz5wjoqx/
You are matching the two \S parts without capturing them:
.replace(/(?<!\w)\'\S(.*?)\S\'(?!\w)/g
// ^^ ^^
So when you replace with the first capture group surrounded by quotes:
'‘$1’'
// ^^
The characters in the \S are not in the (.*?) capture group, so they're not included in the $1 replacement.
Put everything you want to replace with into the capture group:
var result = 'This \'is an\' example'
.replace(
/(?<!\w)'(\S.*?\S)'(?!\w)/g,
'‘$1’'
);
console.log(result)
(also note that ' doesn't need to be escaped in a pattern)
You can also consider using \B ("not a word boundary") instead of negative lookaround for \w, which will make the pattern compatible with older browsers and more concise:
var result = 'This \'is an\' example'
.replace(
/\B'(\S.*?\S)'\B/g,
'‘$1’'
);
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With