Reputation: 55273
The following regex is made to match single quotes that should be replaced by smart right single quote ( ’ ):
It works. But as you can see, it shouldn't match the one in '*text*
. So I modified the regex:
(\S)'(?!\b)|(?=\b)'(?=\b)
The problem now is that it's not only matching the quotes but the other punctuation too:
I'm not a regex expert so I'm not sure how to do it so that only the single quotes are matched in the new regex.
Upvotes: 0
Views: 60
Reputation: 785058
You can use backreference of your captured group #1 in replacement to get back what you've matched using (\S)
:
var re = /(\S)'(?!\b)|(?=\b)'(?=\b)/g;
var str = 'text, \'*text* text?\'\n*It\'s text couldn\'t I\'d text.\'*';
var result = str.replace(re, '$1’');
PS: Your regex can be shortened to:
/(\S)'\B|\b'\b/g
Upvotes: 1
Reputation: 6511
I may be misinterpreting your question, but I think you're trying to match a single quote if it's not preceded by a whitespace. The following regex uses a lookbehind to assert it's in a position preceded by \S
(a non-whitespace character).
/(?<=\S)'/g
Upvotes: 1