用 javascript 中的数组值替换字符串

Replace a string with array values in javascript

我试图通过将字符串值与数组值连接起来,用 javascript 中的数组值替换字符串值。例如:

我的字符串是

var str = 'a*b-ab';
var arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']]

现在,字符串 (str) 有 a、b、ab,数组有 a、b、ab、ac。我们需要连接字符串值,如 a、b 和 ab,并从数组中获取它们的描述。我的输出必须是

class 1 * class 12 - class 15

在 javascript 中有没有办法做到这一点。请帮忙

您可以先将 arrayElement 转换为 Map so that you can easily find the class values from your strings a, b, ab, etc. Then you can use .replace() with the regular expression \w+ 以匹配字符串中的单词元素(即:非运算符)。然后你可以使用一个函数作为 .replace() 的第二个参数来获取匹配的字母,并使用我们制作的 Map 来获取其关联的 class:

const str = 'a*b-ab';
const arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']];

const lookup = new Map(arrayElement);
const res = str.replace(/\w+/g, m => ` ${lookup.get(m)} `).trim();
console.log(res);

如果你需要更好的浏览器支持,可以像这样用ES5重写,很多浏览器都支持,包括IE11:

var str = 'a*b-ab';
var arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']];

var lookup = arrayElement.reduce(function(acc, arr) {
  acc[arr[0]] = arr[1];
  return acc;
}, {});

var res = str.replace(/\w+/g, function(m) {
  return " " + lookup[m] + " ";
}).trim();
console.log(res);