繁体   English   中英

根据对象中的键值条目用值替换字符串中的键

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

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

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

希望它能帮助某人:保持安全:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM