Skip to content Skip to sidebar Skip to footer

Compare An Array To A String And Replace All Items Found In The Array With A Common Character In The String

I have a string of text with 100 different 'keys' between some characters « » and an array containing the UsedKeys. I'm trying to compare the string str to the array and replace

Solution 1:

You can turn the UsedKeys array into a single regexp that will replace all of them, using the | alternative operator. The g modifier makes it replace all occurrences.

var regex = new RegExp(UsedKeys.join('|'), 'g');
var newStr = str.replace(regex, "✔️");

You can then hide all the rest with:

newStr = newStr.replace(/«[^»]*»/g, " ");

Solution 2:

You should use a regular expression.

for (var i = 0; i < UsedKeys.length; i++) { 
    var regex = newRegExp(UsedKeys[i], 'g')
    var a = str.replace(regex, "✔️");
}

The 'g' means globally. So, replace all the occurences.

Post a Comment for "Compare An Array To A String And Replace All Items Found In The Array With A Common Character In The String"