Replace odd matches with typographic opening quote, and even matches with typographic closing quote

StackOverflow https://stackoverflow.com/questions/10617537

Question

I'm trying to replace regular quote symbols ( " ) in a text with typographic quotes (« and »).

Is there a way to replace odd quote matches with « and even matches with » ?

So: Hello "world"! Becomes: Hello «world»!

Also, it shouldn't have any problem if the text doesn't have an even number of quotes, since this is intended to be performed "on the fly"

Thanks for your help!

Était-ce utile?

La solution

/**
 * @param {string} input the string with normal double quotes
 * @return {string} string with the quotes replaced
 */
function quotify(input) {
  var idx = 0;
  var q = ['«', '»'];
  return input.replace(/"/g, function() {
    var ret = q[idx];
    idx = 1 - idx;
    return ret;
  });
}

Autres conseils

I've come up with another way to do this, but I'm not sure which one is more "optimized":

function quotify2(inputStr)
{
    var quotes = inputStr.match(/«|»/g);
    return inputStr.replace(/"/g, (quotes && quotes.length % 2 != 0 ? '»' : '«'));
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top