user3672795
user3672795

Reputation: 153

Replace multiple occurrences of multiple sub-strings in string in jquery

I have a small program that is checking for character sequence in a string against array elements, if a sequence is found in the array terms[] than do something. However this only works for the first instance match in the array for me using the below mechanism. How could I make this happen for multiple occurrences?

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

string given to program is: hello here is me

the program is asked to replace words that are found in a string that match any of the words in the array with the words red and green respectively, however the program stops at the first occurrence found, that is the result from the currently programmed system is:

'red here is me'

Instead of

'red here green me'

How can I alter the below functionality to give me the 2nd result?

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));

I dont think you understood me, i dont care about css, I care about substring replacement.

Here is my current code

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');

Currently my program results in this: this is a three example string of two

I want to fix my program to result in this: this is a three example string of four

Upvotes: 3

Views: 383

Answers (2)

Ori Drori
Ori Drori

Reputation: 191946

Use a String#replace with the replacement function, and alternate between the colors:

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);

And an ES6 version that uses Set and arrow functions:

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);

Upvotes: 2

Keith
Keith

Reputation: 24181

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;
}

Upvotes: 0

Related Questions