Compare an array to a string and replace all items

2019-08-27 18:33发布

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 all keys found in the UsedKey array with check mark character. I'm still very new to loops as well as javascript in general, and I can't seem to get the script to replace any of the keys except for the last one in the array. In this case that would be «SPLXVIII».

I also have a second array called AllKeys which I'd like to use in order to hide all of the non-used keys. I'm certain I'd have to find the difference between the two arrays (UsedKeys and AllKeys), i'm just not quite sure how.

Questions:

1) How can I replace all of the keys in the UsedKey array?

2) How can I hide all of the other keys in the string that aren't in the UsedKey array?

function replace() {
var str = ("«SPII»                

2条回答
Fickle 薄情
2楼-- · 2019-08-27 19:09

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, " ");
查看更多
唯我独甜
3楼-- · 2019-08-27 19:14

You should use a regular expression.

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

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

查看更多
登录 后发表回答