【问题标题】:Replace odd matches with typographic opening quote, and even matches with typographic closing quote将奇数匹配替换为印刷开引号,偶数匹配替换为印刷结束引号
【发布时间】:2012-05-16 11:26:12
【问题描述】:

我正在尝试用印刷引号(« 和 »)替换文本中的常规引号符号( " )。

有没有办法将奇数引号匹配替换为 « 偶数匹配 » ?

所以:你好“世界”! 变成:你好«世界»!

此外,如果文本没有偶数个引号,也不会有任何问题,因为这是为了“即时”执行的

感谢您的帮助!

【问题讨论】:

    标签: javascript regex quotes smart-quotes


    【解决方案1】:
    /**
     * @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;
      });
    }
    

    【讨论】:

    • 谢谢,这正是我想要的!
    【解决方案2】:

    我想出了另一种方法来做到这一点,但我不确定哪个更“优化”:

    function quotify2(inputStr)
    {
        var quotes = inputStr.match(/«|»/g);
        return inputStr.replace(/"/g, (quotes && quotes.length % 2 != 0 ? '»' : '«'));
    }
    

    【讨论】:

    • 在我看来,这会将 all 双引号替换为 »« 而不会在它们之间交替。
    • 它旨在在键入时运行(onKeyUp),因此替换仅替换最后输入的引号。您的功能实际上更加通用,因为它始终适用于整个文本或打字时。我现在正在使用你的版本:)
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多