2016-07-05 29 views
-1

我想从字符串中替换所有字符的存在,但它不起作用。这里是我的代码:如何从jquery中的字符串替换所有字符的存在?

$.each(jsonArray, function (fromString, jtm) { 
    // tempString = tempString.replace(jtm.from, jtm.to) 
    tempString = tempString.replaceAll(jtm.from, jtm.to); 
}); 

我检查使用全局全部更换为Told in this article,但我没有得到我怎么能在我的代码实现。

请帮帮我。

+3

'tempString = tempString.replace(新正则表达式(jtm.from, 'G'),jtm.to)'' –

+0

= tempString tempString.replace(新正则表达式(JTM。 from.replace(/ [| \\ {}()[\]^$ + * ..]/g,'\\ $&'),'g'),jtm.to)' –

+2

@downvoters,please comment –

回答

3

在JavaScript中没有像replaceAll()这样的方法,用于删除所有需要使用带有全局标志的正则表达式。

tempString = tempString.replace(new RegExp(jtm.from,'g'), jtm.to); 


如果字符串包含有特殊意义的正则表达式,然后第一转义字符。

tempString = tempString.replace(new RegExp(jtm.from.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),'g'), jtm.to) 

参见:Converting user input string to regular expression