如何使用jquery将所有双引号替换为单引号?

时间:2011-11-21 04:32:23

标签: jquery string replace

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

我将如何做到这一点。

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

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

2 个答案:

答案 0 :(得分:93)

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

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

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

答案 1 :(得分:1)

您也可以使用 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") 标志; 否则,它会抛出一个类型错误:“replaceAll 必须用 一个全局 RegExp”。