【问题标题】:How to replace all double quotes to single quotes using jquery?如何使用jquery将所有双引号替换为单引号?
【发布时间】:2012-01-02 16:27:03
【问题描述】:

我需要使用 jquery 将所有双引号替换为单引号。

我将如何做到这一点。

我使用此代码进行了测试,但它无法正常工作。

newTemp = newTemp.mystring.replace(/"/g, "'");

【问题讨论】:

    标签: jquery string replace


    【解决方案1】:

    使用双引号将引号括起来或转义。

    newTemp = mystring.replace(/"/g, "'");
    

    newTemp = mystring.replace(/"/g, '\'');
    

    【讨论】:

    • 这是破坏性的替换。
    • 如果有人需要转义里面的单引号而 '\'' 不起作用,请尝试使用 text.replace(/'/g, "‘");
    • /g是什么意思?
    • @ParthSavadiya 它代表“全球”。这是一个replaceAll,它不会在第一次出现时停止。 https://javascript.info/regexp-introduction#flags
    【解决方案2】:

    您也可以使用replaceAll(search, replaceWith) [MDN]。

    然后,通过将一种类型的引号包装成不同的类型来确保你有一个字符串:

     'a "b" c'.replaceAll('"', "'")
     // result: "a 'b' c"
        
     'a "b" c'.replaceAll(`"`, `'`)
     // result: "a 'b' c"
    
     // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
     'a "b" c'.replaceAll(/\"/g, "'")
     // result: "a 'b' c"
    

    如果您选择正则表达式,则重要():

    当使用regexp 时,您必须设置全局 ("g") 标志; 否则,它会抛出一个 TypeError: "replaceAll must be called with 一个全局正则表达式”。

    【讨论】:

      猜你喜欢
      • 2012-01-01
      • 2013-04-15
      • 2011-06-24
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多