根据对象中的键值条目,用值替换字符串中的键 [英] Replace keys in string by value based on key–value entries in object

查看:44
本文介绍了根据对象中的键值条目,用值替换字符串中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我将输出扩展为:

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

推荐答案

我只是在脑子里做这个,但这应该可行.

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

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

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.

您也可以使用jQuery来做到这一点,但这可能有点过头了:

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

这篇关于根据对象中的键值条目,用值替换字符串中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆