Javascript utf8_encode
Encodes an ISO-8859-1 string to UTF-8
Examples
Example 1
Running
1.utf8_encode('Tom van Mikes');
Could return
1.'Tom van Mikes'
Dependencies
No dependencies, you can use this function standalone.
function utf8_encode ( string ) {
// Encodes an ISO-8859-1 string to UTF-8
//
// version: 812.316
// discuss at: http://phpjs.org/functions/utf8_encode
// + original by: Webtoolkit.info (http://www.webtoolkit.info/)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: sowberry
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + improved by: Yves Sucaet
// + bugfixed by: Onno Marsman
// * example 1: utf8_encode('Tom van Mikes');
// * returns 1: 'Tom van Mikes'
string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = "";
var start, end;
var stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if((c1 > 127) && (c1 < 2048)) {
enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
}
if (enc != null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n+1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
}
|
HTML code for linking to this page:
Related in same category :
-
|
|