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

DEV*_*OPS 38 string jquery replace

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

我将如何做到这一点.

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

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

ami*_*t_g 99

使用双引号括起引用或转义它.

newTemp = mystring.replace(/"/g, "'");
Run Code Online (Sandbox Code Playgroud)

要么

newTemp = mystring.replace(/"/g, '\'');
Run Code Online (Sandbox Code Playgroud)


Raz*_*Raz 5

您还可以使用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"
Run Code Online (Sandbox Code Playgroud)

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

使用 a 时,regexp您必须设置全局(“g”)标志;否则,它将抛出 TypeError:“replaceAll 必须使用全局 RegExp 调用”。