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\
Object keys cannot be RegExp objects. You must use a string or a valid ID. That being said, you could do something like this:
var kv = {
"/key/g": "value"
};
I'm curious. Why do you want to do this?
EDIT: I am partially mistaken. RegExp objects can be used as keys, but not using the object literal syntax. See jmar777's answer.
You can also use an expression as a key by wrapping it in []
when creating an object:
var kv = {
[/key/g] : "value"
};
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"
/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 :)
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
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
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
I think this question deserves an updated answer. Since ES6, a new type (standard built-in object) called Map was created to cover cases like this one among others.
A Map is very similar to an Object, except it allows any type as key.
Map.prototype.forEach() can then be used to loop over each key/value pair.
In your case, your function could now be:
function fixUnicode(text) {
var result = text;
var replaceMap = new Map();
replaceMap.set(/é/g, "é");
replaceMap.set(/è/g, "è");
replaceMap.set(/ê/g, "ê");
replaceMap.set(/ë/g, "ë");
replaceMap.set(/Ã /g, "à");
replaceMap.set(/ä/g, "ä");
replaceMap.set(/â/g, "â");
replaceMap.set(/ù/g, "ù");
replaceMap.set(/û/g, "û");
replaceMap.set(/ü/g, "ü");
replaceMap.set(/ô/g, "ô");
replaceMap.set(/ö/g, "ö");
replaceMap.set(/î/g, "î");
replaceMap.set(/ï/g, "ï");
replaceMap.set(/ç/g, "ç");
replaceMap.forEach(function (newString, old) {
result = result.replace(old, newString);
});
return result;
}
You can read more about maps at MDN