javascriptregexquotessmart-quotes

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


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!


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;
      });
    }