【问题标题】:Jquery: Replace string with values from an arrayJquery:用数组中的值替换字符串
【发布时间】:2012-11-25 03:58:43
【问题描述】:

假设我有这样的事情:

var array = [cat,dog,fish];
var string = 'The cat and dog ate the fish.';

我想从字符串中清除所有这些值

var result = string.replace(array,"");

结果最终会是:The and ate the .

现在,replace() 似乎只替换了数组中的一个值。我怎样才能使它在字符串中替换数组中的所有/多个值?

谢谢!

【问题讨论】:

  • 闻起来像家庭作业。那么你的例子是无效的,运行数组行会抛出错误。您是否曾经使用过for 循环或each()new RegExp()?提示,试试看。

标签: javascript jquery arrays replace


【解决方案1】:

您要么创建自定义regexp,要么循环遍历字符串并手动替换。

array.forEach(function( word ) {
    string = string.replace( new RegExp( word, 'g' ), '' );
});

var regexp = new RegExp( array.join( '|' ), 'g' );

string = string.replace( regexp, '' );

【讨论】:

    【解决方案2】:
    string.replace(new RegExp(array.join("|"), "g"), "");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 2014-02-01
      • 1970-01-01
      • 2016-06-22
      • 2013-06-03
      • 2017-06-09
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多