在javascript中替换字符串中的多个字符
我有这个漂亮的代码,我不知道为什么不工作。它应该获得文本输入的值,并将每个给定的国家字符替换为其HTML代码,以实现兼容性。但是,当我单击按钮,该函数返回字符串没有任何更改。
任何想法?
I got this nice code, which I have no idea why doesn't work. It should get the value of a text input and replace each given national character with it's HTML code, for compatibility purposes. But, when I click the button, the function returns the string without any changes. Any idea?
( jsfiddle )
<a id="reminder1" onclick="document.getElementById('reminder2').style.display = ''; document.getElementById('reminder1').style.display = 'none';">
Set reminder
</a>
<a id="reminder2" class="reminder" style="display:none;">
<input type="text" id="reminderh" size=40 style="font-size:20px;">
<input type="button" value="Set" onclick="csere(document.getElementById('reminderh').value);">
</a>
<script>
function csere(qwe){
document.getElementById('reminder2').style.display = 'none';
var rtz0 = qwe.replace("á","á");
var rtz1 = rtz0.replace("Á","Á");
var rtz2 = rtz1.replace("é","é");
var rtz3 = rtz2.replace("É","É");
var rtz4 = rtz3.replace("í","í");
var rtz5 = rtz4.replace("Í","Í");
var rtz6 = rtz5.replace("ö","ö");
var rtz7 = rtz6.replace("Ö","Ö");
var rtz8 = rtz7.replace("ő","&ő");
var rtz9 = rtz8.replace("Ő","Ő");
var rtz10 = rtz9.replace("ó","ó");
var rtz11 = rtz10.replace("Ó","Ó");
var rtz12 = rtz11.replace("ü","ü");
var rtz13 = rtz12.replace("Ü","Ü");
var rtz14 = rtz13.replace("ű","ű");
var rtz15 = rtz14.replace("Ű","Ű");
var rtz16 = rtz15.replace("ú","ú");
var uio = rtz16.replace("Ú","Ú");
//Creates a cookie with the final value (different function)
createCookie('reminder',uio,1500);
document.getElementById('reminder1').style.display = '';
}
</script>
您可以replace 所有程式,不使用命名实体:
You can just replace everything programmatically, not using named entities:
return input.replace(/[^ -~]/g, function(chr) {
// ^^^^^^
// this is a regexp for "everything than printable ASCII-characters"
// and even works in a ASCII-only charset. Identic: [^\u0020-\u007E]
return "&#"+chr.charCodeAt(0)+";";
});
如果要使用命名实体,可以将其与键值映射像@jackwanders的答案):
If you want to use named entities, you can combine this with a key-value-map (as like in @jackwanders answer):
var chars = {
"á" : "á",
"Á" : "Á",
"é" : "é",
"É" : "É",
...
}
return input.replace(/[^ -~]/g, function(chr) {
return (chr in chars)
? chars[chr]
: "&#"+chr.charCodeAt(0)+";";
});
但是,您永远不需要使用html实体在JavaScript中。使用UTF8作为一切的字符编码,它将工作。
However, you should never need to use html entities in JavaScript. Use UTF8 as the character encoding for everything, and it will work.