【问题标题】:jQuery replace match word with each methodjQuery用每个方法替换匹配词
【发布时间】:2015-01-20 15:14:46
【问题描述】:

如何用每种方法替换文本?

对吗?它不能正确替换/找到文本

$(function(){

   var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
   var cur_style = $('#obj').attr('class');
   var new_style;

   $(style_find).each(function(i,cl){
      new_style = cur_style.replace(cl,'new-class'); 
      // it doesnt replace the whole word
   });

})

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

String.prototype.replace() 的行为取决于它的第一个参数的类型。考虑这段代码:

var example = "str str str str"; 
example = example.replace("str", "bob"); 
console.log(example === "bob str str str"); // === true?

我给replace() 一个字符串作为它的第一个参数。当您这样做时,它只会替换第一次出现的子字符串。

当您使用 RegExp 调用 replace() 时,您会得到返回所有匹配项的内容

var example = "str str str str"; 
example = example.replace(/str/g, "bob"); 
console.log(example === "bob bob bob bob"); // === true

我们需要的是一个匹配你想要替换的所有内容的正则表达式。

var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var regexp = (function() { 
  var inner = ""; 
  style_find.forEach(function(el) { 
    inner = inner + el + "|";   
  }); 
  return new RegExp(inner, "g"); 
}());

使用regexp,我可以将您的代码修改为:

$(function(){
   var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
   var cur_style = $('#obj').attr('class');
   var new_style = cur_style.replace(regexp, 'new-class'); 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多