wyc
wyc

Reputation: 55273

Matching opening and closing quote in JavaScript (simple quotes)

I wanted to change all the simple quotes ("…") of a string to smart quotes (“…”):

str.replace(/"/g,'“');

But then I realized that, in order to do it, I have to match the opening and closing quote, something like this:

str.replace(/REGEX_FOR_OPENING_QUOTES/g,'“');
str.replace(/REGEX_FOR_CLOSING)_QUOTES/g,'”');

What regex should I use in this case?

Upvotes: 3

Views: 1850

Answers (3)

nhahtdh
nhahtdh

Reputation: 56809

Another solution, if you need to make sure that " forms a pair and you assume that two nearest double quotes should be matched:

input.replace(/"([^"]*)"/g, "“$1”");

Example run:

'"test" dskfjsdfklds "sdfsdf" "'.replace(/"([^"]*)"/g, "“$1”");

Output:

“test” dskfjsdfklds “sdfsdf” "

(The last " is not converted, since it does not form a pair)

Upvotes: 2

anubhava
anubhava

Reputation: 785098

You can use lookahead based regex:

var s = 'abc "quoted string" foo bar "another quoted text" baz';
var r = s.replace(/"(?=(([^"]+"){2})*[^"]*"[^"]*$)/g, '<').replace(/"/g, '>');
//=> abc <quoted string> foo bar <another quoted text> baz

PS: Replace < and > by and .

Trick is to find " that is followed by odd number of " using this lookahead first: (?=(([^"]+"){2})*[^"]*"[^"]*$). Then remaining closing " can be replaced by .

Upvotes: 1

alexpls
alexpls

Reputation: 1964

This is a pretty naive approach which loops through every regular quote and toggles it between a smart open and close quote, but it may work for you...

function addSmartQuotes(str) {
  var open = false;
  return str.replace(/"/g, function(match, $1) {
    open = !open;
    return open ? '“' : '”';
  });
}

var str = 'This is my "string", blahdy "blah" blah';
console.log(addSmartQuotes(str)); // => This is my “string”, blahdy “blah” blah

It's also worth noting that unless you're sure that your page is in UTF-8, it's best to use HTML character codes for the open and closing quotes instead of the UTF-8 characters. These are &ldquo; (“) and &rdquo; (”).

Upvotes: 2

Related Questions