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

大憨熊 提交于 2021-02-04 13:56:13

问题


I’m trying to convert each integer in a string to its corresponding value in an object based on its key–value entries. For example if I have:

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

I would expext the output to be:

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

回答1:


I'm just doing this off the top of my head, but this should work.

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(key, arr[key]);
}

If you wanted all occurrences of the number to be replaced, you'd need to incorporate a Regex into the mix:

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

Also, I'd pick another name other than arr, as that implies it's an array when it's clearly an object. Also, make sure you only use for-in loops on objects, not arrays, because of issues with prototype leakage and others.

You can also do this with jQuery, but it's probably overkill:

var new_str = str;

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



回答2:


You could also use a reducer here which looks cleaner in my opinion:

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



回答3:


2021:

Do take care that

value 3

also matches

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)



回答4:


Suppose you have an object like arr, with str defined and new_str declared. Then, assuming that we aim for a general solution the following works:

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

Just as a little side note, arr given your example is an Object. (I realize that they are sometimes called associative arrays as well; just pointing it out).




回答5:


Using regex, an alternative solution could be like this:

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



回答6:


I recently needed to replace a string with key: value entries of an object, where some keys contain special characters such as curly brackets. So, as others have suggested we can use the String.replace function with a RegExp passing a function as the replacement value, but there's a problem with creating a RegExp itself, since we would need to escape all special characters in it with \. Here's the escaping function and the final replacement function with an example:

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

Hope it helps somebody! Stay safe :)



来源:https://stackoverflow.com/questions/11199565/replace-keys-in-string-by-value-based-on-key-value-entries-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!