简体   繁体   中英

Encoding and JS - how to remove accents with javascript from a UTF-8 text

I have this option on a webpage, that double clicking on a word, it opens a new window and performs a search. I used a short javascript function (like RemoveAccents() or accentsTidy()) to remove accents from the word, and pass the word as a string in the new window's url. Now I changed the encoding of the site and use UTF-8 encoding in the declaration, and encode the text with UTF-8, as it's mostly in French, using the PHP function iconv("ISO-8859-1", "UTF-8", $string) (iconv("Windows-1252"...) doesn't solve the problem).

But with UTF-8 encoding, the javascript function does not remove the accents, and the new window is blank when the url has accents in it.

It works fine when I switch back to ISO-8859-1 encoding for the page.

I tested the functions with alert(string) and they work fine except for the accents which are not replaced with their equivalent letter, the only error message on the JS log of the new window is about the encoding not being declared, which is obvious as the page is blank when there is an accent in the url...

I also tested with accents in the url on other pages and I don't see any problem, if not for the needed decoding/encoding that follows.

I found this function while searching for Unicodes escapes, applying it before the remove-accent function is doing the trick :

String.prototype.removeDiacritics = function() {
var diacritics = [
    [/[\300-\306]/g, 'A'],
    [/[\340-\346]/g, 'a'],
    [/[\310-\313]/g, 'E'],
    [/[\350-\353]/g, 'e'],
    [/[\314-\317]/g, 'I'],
    [/[\354-\357]/g, 'i'],
    [/[\322-\330]/g, 'O'],
    [/[\362-\370]/g, 'o'],
    [/[\331-\334]/g, 'U'],
    [/[\371-\374]/g, 'u'],
    [/[\321]/g, 'N'],
    [/[\361]/g, 'n'],
    [/[\307]/g, 'C'],
    [/[\347]/g, 'c'],
];
var s = this;
for (var i = 0; i < diacritics.length; i++) {
    s = s.replace(diacritics[i][0], diacritics[i][1]);
}
return s;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM