我想用其他字符替换字符串中的某些字符.我做了我的研究,发现最好的方法是使用正则表达式...但是,有些东西不起作用......这就是我到目前为止所做的...
var alphabet = {
'á':'a',
'é':'e',
'í':'i'
};
var word = $("input[name=phrase]").val();
alert(word); //output: ok!
var url = word.replace(/áéí|/g, function(s) {
return alphabet[s];
});
alert(url); //output: undefined,undefined,undefined...
Run Code Online (Sandbox Code Playgroud)
使用匹配任何这些字符[],并使用匹配来()捕获匹配,而不是查找这些连续字符的匹配.
var url = word.replace(/[áéí]/g, function(s) {
return alphabet[s];
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/5UmLV/1/
如@Felix Kling所述,捕获组是不必要的.更新以反映这一改进.