【问题标题】:How to replace all existence of chars from string in jquery?如何从jquery中的字符串替换所有存在的字符?
【发布时间】:2016-07-05 05:20:52
【问题描述】:

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

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

我检查了使用 global 将所有替换为 Told in this article,但我不知道如何在我的代码中实现。

请帮助我。

【问题讨论】:

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

标签: jquery arrays json string replace


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2019-08-31
    • 2011-02-23
    • 2020-02-28
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多