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

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

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!

有帮助吗?

解决方案

/**
 * @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;
  });
}

其他提示

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 ? '»' : '«'));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top