根据对象中的键值条目,将字符串中的键替换为值

Replace keys in string by value based on key–value entries in object

本文关键字:字符串 替换 对象 键值      更新时间:2023-09-26

我正在尝试根据其键值条目将字符串中的每个整数转换为对象中的相应值。例如,如果我有:

var arr = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
  };
var str = "I want value 3 here and value 234 here";

我将输出扩展为:

new_str = "I want value_three here and value other_value here"

我只是在头顶上做这件事,但这应该有效。

var new_str = str;
for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }
    new_str = new_str.replace(key, arr[key]);
}

如果您希望替换所有出现的数字,则需要将正则表达式合并到组合中:

var new_str = str;
for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }
    new_str = new_str.replace(new RegExp(key, "g"), arr[key]);
}

另外,我会选择arr以外的其他名称,因为这意味着当它显然是一个对象时它是一个数组。此外,请确保仅在对象上使用for-in循环,而不是数组,因为原型泄漏等问题。

你也可以用jQuery做到这一点,但这可能是矫枉过正:

var new_str = str;
$.each(arr, function (key, value) {
    new_str = new_str.replace(key, value);
});

假设你有一个像 arr 这样的对象,定义并声明了str new_str。然后,假设我们的目标是一个通用解决方案,则以下工作:

var arr = { "3": "value_three", "6": "value_six", "234": "other_value" };
var str = "I want value 3 here and value 234 here";
// Building a regex like `/3|6|234/g`
let re = new RegExp(Object.keys(arr).join('|'), 'g');
// Arrow function is approximately equivalent to
// an anonymous function like `function(match) { return arr[match]; }`
new_str = str.replace(re, match => arr[match]);
console.log(new_str);

作为一点旁注,arr给出您的示例是一个Object。(我意识到它们有时也被称为关联数组;只是指出来)。

你也可以在这里使用一个在我看来看起来更干净的减速器:

new_str = Object.keys(dynamicValues).reduce((prev, current) => {
  return prev.replace(new RegExp(current, 'g'), dynamicValues[current]);
}, value);

2021

一定要注意

value 3

也匹配

value 32

const arr = {'3':'value_three', '6':'value_six', '234':'other_value'};
let str = 'I want value 3 here and value 234 here';
Object.keys(arr).forEach(key => str = str.replaceAll(`value ${key}`,arr[key]))
console.log(str)

使用 regex ,另一种解决方案可以是这样的:

const object = {
    "3": "value_three",
    "6": "value_six",
    "234": "other_value"
};
const str = "I want value 3 here and value 234 here. value 32";
const replacedText1 = str.replace(/value 'd+/g, v=>object[v.split(" ")[1]] || v);
const replacedText2 = str.replace(/'d+/g, v=>object[v] || v);
console.log(replacedText1);
console.log(replacedText2);

我最近需要用对象的key: value条目替换字符串,其中某些键包含特殊字符,例如大括号。因此,正如其他人建议的那样,我们可以将 String.replace 函数与 RegExp 一起使用,将函数作为替换值传递,但是创建 RegExp 本身存在问题,因为我们需要用 ' 转义其中的所有特殊字符。下面是转义函数和最终替换函数的示例:

// Escape string to use it in a regular expression
const regexpEscape = (string) => string.replace(/[.*+'-?^${}()|[']'']/g, '''$&');
// Replace string with `key: value` entries of the search object.
const stringReplace = (string, search) => {
  const regexp = new RegExp(
    Object.keys(search)
      .map((item) => regexpEscape(item))
      .join('|'),
    'g'
  );
  return string.replace(regexp, (match) => search[match]);
};
const search = {
   '{{name}}': 'John',
   '{{lastname}}': 'Doe',
   '{{age}}': 24,
};
const template = 'Hey, {{name}} {{lastname}}! Your age is {{age}}.';
console.log(stringReplace(template, search));

希望它对某人有所帮助!:)保持安全