【问题标题】:Replace multiple occurrences of multiple sub-strings in string in jquery替换jquery中字符串中多次出现的多个子字符串
【发布时间】:2017-04-16 04:58:39
【问题描述】:

我有一个小程序,它正在根据数组元素检查字符串中的字符序列,如果在数组 terms[] 中找到序列,则执行某些操作。但是,这仅适用于我使用以下机制的数组中的第一个实例匹配。我怎样才能使这种情况发生多次?

示例:terms = ['hello', 'world', 'this', 'is', 'me']

给程序的字符串是:hello here is me

要求程序将在字符串中找到的与数组中的任何单词匹配的单词分别替换为单词 red 和 green,但是程序在找到的第一个匹配项处停止,即当前的结果程序化系统是:

'red here is me'

代替

'red here green me'

如何更改以下功能以提供第二个结果?

for (var i = 0; i < terms.length && !match; i++) {
    if (string.indexOf(terms[i]) > -1) {
        match = true;
        var newString = '';
        wrapper.css("background", "#a1e4ff");
        var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i]) + terms[i].length));

我不认为你理解我,我不关心 css,我关心子字符串替换。

这是我当前的代码

function check(string) {
    var terms = ['one', 'two'];
    var match = false;

    for(var i=0;i<terms.length;i++) {

        if(string.indexOf(terms[i]) > -1) {
            match = true;
            var newString='';
            var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i])+terms[i].length));

            switch(matchString) {
                case 'one':
                newString = string.replace(matchString, "three");
                break;
              case 'two':
                newString = string.replace(matchString, "four");
              default:
                alert('no matches');
            }

            $("ul").append("<li>" + newString + "</li>");
        }
      }
    }

check('this is a one example string of two');

目前我的程序结果如下: 这是 two

three 示例字符串

我想修复我的程序以实现以下结果: 这是 four

three 示例字符串

【问题讨论】:

  • 你是说它在红/绿之间交替出现..?

标签: javascript jquery arrays string replace


【解决方案1】:

使用带有替换功能的String#replace,并在颜色之间交替:

function replaceWithColor(str, terms) {
  var termsDict = terms.reduce(function(d, t) {
    d[t] = true;
    return d;
  }, Object.create(null));
  
  var colors = ['red', 'green'];

  var i = 0;

  return str.replace(/\w+/g, function(t) {
    return termsDict[t] ? colors[i++ % 2] : t;
  });
}

var terms = ['hello', 'world', 'is', 'me'];

var str = "hello here this is me";

var result = replaceWithColor(str, terms)

console.log(result);

还有一个使用 Set 和箭头函数的 ES6 版本:

const replaceWithColor = (str, terms) => {
  const termsSet = new Set(terms);
  
  const colors = ['red', 'green'];

  let i = 0;

  return str.replace(/\w+/g, (t) => termsSet.has(t) ? colors[i++ % 2] : t);
}

var terms = ['hello', 'world', 'is', 'me'];

var str = "hello here this is me";

var result = replaceWithColor(str, terms)

console.log(result);

【讨论】:

  • 这并不容易,考虑terms = ['is']str = "this"
  • 确实如此。将它们包裹在空格内应该可以解决此问题。你怎么看?
  • 我已经可以更改在数组中找到的第一个匹配项,但如果有第二个匹配项,它就不起作用。也许我可以以某种方式更改代码以循环多次相同的字符串?
  • 我改变了逻辑。找一个词,看看它是否在terms,然后才替换它。我将创建一个术语字典以提高性能。
【解决方案2】:

var terms = ['hello', 'world', 'this', 'is', 'me'];


function check(str) {
  var 
   s = str.split(' ');
   out = [],
   redgreen = ['red','green'],
   rgcount = 0;
  
  s.forEach(function (k, i) {
    if (terms.indexOf(k) >= 0) {
      var color = redgreen[rgcount];
      out.push('<span class="'+color+'">'+color+'</span>');
      rgcount = (rgcount + 1) % 2;
    } else out.push(k);
  });
  document.write(out.join(' ')+'<br/>');
}

check('hello here is me');
check('one two there is three four pink yelow there is this what yet there');
check(terms.join(' '));
.red {
  color: red
}
.green {
  color: green;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2016-09-10
    • 2021-11-24
    • 1970-01-01
    • 2021-06-13
    • 2016-05-07
    相关资源
    最近更新 更多