如何使用RegExp文字作为对象键? [英] How to use a RegExp literal as object key?

查看:95
本文介绍了如何使用RegExp文字作为对象键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用创建一个包含正则表达式作为键值的对象。我尝试使用以下语法:

I would like to use create a object that contains regular expressions as the key value. I tried to use the following syntax:

var kv = {
    /key/g : "value"
};

但是根据它失败了JavaScript lint

SyntaxError: invalid property id

我该如何解决?

背景:我想这样做的原因是为了实现修复HTTP API结果中错误的unicode的解决方法。我知道这是非常hackish,但由于我无法控制API服务器代码,我认为这是我能做的最好的。

Background: The reason why I want to do this is to implement a workaround that fixes wrong unicode in a HTTP API result. I know this is very hackish, but since I have no control over the API server code I think this is the best I can do.

目前我实现了映射键数组和值数组:

Currently I implemented the mapping by having a keys array and a values array:

function fixUnicode(text) {

    var result = text;
    var keys = [];
    var values = [];
    keys.push(/é/g); values.push("é");
    keys.push(/è/g); values.push("è");
    keys.push(/ê/g); values.push("ê");
    keys.push(/ë/g); values.push("ë");
    keys.push(/à/g); values.push("à");
    keys.push(/ä/g); values.push("ä");
    keys.push(/â/g); values.push("â");
    keys.push(/ù/g); values.push("ù");
    keys.push(/û/g); values.push("û");
    keys.push(/ü/g); values.push("ü");
    keys.push(/ô/g); values.push("ô");
    keys.push(/ö/g); values.push("ö");
    keys.push(/î/g); values.push("î");
    keys.push(/ï/g); values.push("ï");
    keys.push(/ç/g); values.push("ç");

    for (var i = 0; i < keys.length; ++i) {
        result = result.replace(keys[i], values[i]);
    }
    return result;
}

但我想实现使用JavaScript对象将键映射为值:

But I want to implement to use a JavaScript object to map keys as values:

function fixUnicode(text) {

    var result = text;
    var keys = {
        /&Atilde;&copy;/g : "&eacute;",
        /&Atilde;&uml;/g :  "&egrave;"
        // etc...
    };

    for (var key in keys) {
        result = result.replace(key, keys[key]);
    }
    return result;
}


推荐答案

这可以做到,但是不使用对象文字语法。你需要这样做:

This can be done, but not using object literal syntax. You'll need to do it like this:

var kv = {};
kv[/key/g] = "value";
console.log(kv[/key/g]); // "value"



编辑:这可能会使用一些解释。正如xanatos在下面评论的那样,这里真正发生的是,在这种情况下, / key / g 的密钥是 toString()'d创建密钥。这一点很重要,因为它会对密钥的唯一性产生影响。请考虑以下事项:


this could probably use some explaining. As xanatos commented below, what's really happening here is that the key, /key/g in this case, is being toString()'d to create the key. This is important to know, because it has an effect on key uniqueness. Consider the following:

var x = {},
    reg = /foo/;

x[reg] = 'bar';
console.log(x[reg]); // "bar"
console.log(x[reg.toString()]); // "bar"
console.log(x['/foo/']); // "bar'

总之,我半害怕问为什么你需要这样做,但假设你有理由,要小心并确保你理解实际发生了什么:)

In summary, I'm semi-scared to ask why you need to do this, but assuming you have your reasons, be careful and make sure you understand what is really happening :)



编辑2:因此,为了回应您更新的问题,您应该能够实现与您想要的非常接近的东西。只要您将正则表达式包装在内,就可以使用对象文字语法不幸的是,这意味着您必须手动重建该密钥中的实际RegExp对象。例如:


Edit 2: So in response to your updated question, you should be able to achieve something pretty close to what you want. You can use the object literal syntax as long as you wrap the regular expression in quotes. Unfortunately that means you'll have to manually reconstruct an actually RegExp object out of that key though. For example:

var result = "abcdef",
    replacements = {
        "/a/g": "FOO",
        "/d/i": "BAR"
    };

for (var key in replacements) {
    var parts = key.split('/');
    result = result.replace(new RegExp(parts[1], parts[2]), replacements[key]);
}

console.log(result); //FOObcBARef



编辑3:因为,为什么不呢。我一直坚持让你的对象文字语法工作,我没有考虑到你不需要实际查找模式本身的替换(即,根本不需要对象键)。这是一种使用不需要RegExp重建的数组的更有效的方法:


Edit 3: Because, why not. I was so stuck on making your object-literal syntax work, that I didn't consider the fact that you never need to actually look up the replacement by the pattern itself (i.e., there's no need for object keys at all). Here's a more efficient approach using arrays that doesn't require the RegExp reconstruction:

var result = "abcdef",
    replacements = [
        [/a/g, "FOO"],
        [/d/i, "BAR"]
    ];

for (var i = 0, len = replacements.length; i < len; i++) {
    var replacement = replacements[i];
    result = result.replace(replacement[0], replacement[1]);
}

console.log(result); //FOObcBARef



编辑4:因为我很无聊而且我喜欢这个问题。这是忍者版本:


Edit 4: Because I'm bored and I like this question. Here's the ninja version:

var result = "abcdef",
    replacements = [
        [/a/g, "FOO"],
        [/d/i, "BAR"]
    ], r;

while ((r = replacements.shift()) && (result = String.prototype.replace.apply(result, r))) {}

console.log(result); //FOObcBARef

这篇关于如何使用RegExp文字作为对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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