【发布时间】:2012-01-02 16:27:03
【问题描述】:
我需要使用 jquery 将所有双引号替换为单引号。
我将如何做到这一点。
我使用此代码进行了测试,但它无法正常工作。
newTemp = newTemp.mystring.replace(/"/g, "'");
【问题讨论】:
我需要使用 jquery 将所有双引号替换为单引号。
我将如何做到这一点。
我使用此代码进行了测试,但它无法正常工作。
newTemp = newTemp.mystring.replace(/"/g, "'");
【问题讨论】:
使用双引号将引号括起来或转义。
newTemp = mystring.replace(/"/g, "'");
或
newTemp = mystring.replace(/"/g, '\'');
【讨论】:
您也可以使用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 一个全局正则表达式”。
【讨论】: