string.replace(“é”, “e”) 不起作用
string.replace("é", "e") not working
我有一个应该"清理"字符串的函数,我想使用 replace() 来做到这一点,但我无法弄清楚为什么当文本来自输入时以下代码不起作用[文本]。
例如:
console.log(getCleanText("ééé")); // works fine, it displays : eee
但
// my_id is an input with type="text"
var my_text = document.getElementById("my_id").value
console.log(getCleanText(my_text)); // doesn't work at all, it displays : ééé
函数代码为:
function getCleanText(some_text) {
var clean_text = some_text.toLowerCase();
clean_text = clean_text.replace("é", "e");
clean_text = clean_text.split("é").join("e"); // give it another try
return clean_text;
}
知道吗?
我敢打赌你的问题在于对Unicode的误解。
é
é
上面的两个字符是两个不同的字符。 第一个是字母 e,带有重音字符 (U+0301)。另一个是单个字符,U+00E9。
您需要确保替换两个版本。
我认为元素值中的字符"é"与"é"常量不同。要解决此问题,您可以查看输入的 int 值。
var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);
然后,您将能够检测到要替换的字符。
如果您只想从文本中删除重音符号,请查看问题 删除 JavaScript 字符串中的重音符号/音调符号
试试这个:
function getCleanText(old_string)
{
var new_string = old_string.toLowerCase();
return new_string.replace(/é/g, 'e');
}
艾德:被罗伯特殴打。有关参考,请参阅此处:扩展内置对象的有用 JavaScript 方法有哪些?
试试这个:
function cleanText(text) {
var re = new RegExp(/'u0301|'u00e9/g);
return text.replace(re, "e").toLowerCase();
}
cleanText("éééé")
--
更新为使用 Matt Grande 提议的 UniCode 字符
的输出是什么 var my_text = document.getElementById("my_id").value;
?根据您的 html,您可能需要使用其他函数来获取数据。例如 var my_text = document.getElementById("my_id").innerHTML
;
http://jsbin.com/obAmiPe/5/edit?html,js,console,output
相关文章:
- 替换变量时,JavaScript字符串replace()不起作用
- 使用replace方法替换innerHTML以及在Javascript中不起作用的正则表达式
- string.replace(“é”, “e”) 不起作用
- .replace 在 for 循环中不起作用吗?
- JavaScript Location.replace 不起作用
- YouTube ajax, .replace() 不起作用
- window.location.replace() 在窗体中不起作用
- JavaScript .replace() 部分的 url 不起作用
- 字符串正则表达式模式.replace(/{0}/, “$0.00”) 不起作用
- 使用window.location.replace重定向不起作用
- window.location.replace不起作用
- Javascript Regex replace在IE10中不起作用
- window.location.replace在客户端不起作用
- 如果重新加载了同一页,window.location.replace将不起作用
- Javascript replace()方法不起作用
- 试图更改onchange中的所有数字-onchange.replace没有'不起作用
- replace()函数在ie浏览器中不起作用
- Javascript中的Replace All不起作用
- 当我试图通过rails插入URL时,window.replace方法在js中不起作用
- Parameters .replace()两次jQuery插件不起作用