Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the following regex removing the bounding characters inside single quotes?

This code turns straight single quotes into curly single quotes:

var result = 'This \'is an\' example'.replace(/(?<!\w)\'\S(.*?)\S\'(?!\w)/g, '&lsquo;$1&rsquo;')
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/

like image 758
alexchenco Avatar asked Dec 09 '25 08:12

alexchenco


1 Answers

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:

'&lsquo;$1&rsquo;'
//      ^^

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,
    '&lsquo;$1&rsquo;'
  );
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,
    '&lsquo;$1&rsquo;'
  );
console.log(result)
like image 140
CertainPerformance Avatar answered Dec 10 '25 22:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!