string.replace(“é”, “e”) 不起作用

string.replace("é", "e") not working

本文关键字:不起作用 replace string      更新时间:2023-09-26

我有一个应该"清理"字符串的函数,我想使用 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