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

I have function that is supposed to "clean" a string and i'd like to use replace() to do that, but I can't figure out why the following code is not working when the text comes from an input[text].

for instance :

console.log(getCleanText("ééé")); // works fine, it displays : eee

but

// 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 : ééé

the function code is :

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;
}

any idea ?


I think the character "é" from element value is the different from the "é" constant. To resolve that you can take look at the int value of the input.

var inputEValue = document.getElementById("my_id").charCodeAt(0);
var constantEValue = "é".charCodeAt(0);

Then you will be able to detect what characters you are replacing.
If you want to just remove accents from text, take look at the question Remove accents/diacritics in a string in JavaScript


I'm willing to bet your problem lies in a misunderstanding of Unicode.

é 
é

Those two characters above are two different characters. The first is the letter e, with an accent character (U+0301). The other is a single character, U+00E9.

You need to ensure you're replacing both versions.


Try this:

function getCleanText(old_string)
{
    var new_string = old_string.toLowerCase();
    return new_string.replace(/é/g, 'e');
}

Ed: beaten by the Robert. For reference, see here: What are useful JavaScript methods that extends built-in objects?

链接地址: http://www.djcxy.com/p/94030.html

上一篇: jQuery表格行构建器

下一篇: string.replace(“é”,“e”)不起作用