Tuesday, 15 March 2011

javascript - Converting Arabic numerals to Arabic/Persian numbers in html file -



javascript - Converting Arabic numerals to Arabic/Persian numbers in html file -

i trying convert plain text standard arabic numerals eastern standard arabic digits. taking 1 2 3... , converting them ١‎ ٢‎ ٣‎.... function converts all numbers, including numbers contained within tags, i.e. h1.

private void loadhtmlfile(object sender, eventargs e) { var htmlfile = "<html><body><h1>i born in 1988</h1></body></html>".toarabicnumber(); ; webbrowser1.documenttext=htmlfile; } } public static class stringhelper { public static string toarabicnumber(this string str) { if (string.isnullorempty(str)) homecoming ""; char[] chars; chars = str.tochararray(); (int = 0; < str.length; i++) { if (str[i] >= '0' && str[i] <= '9') { chars[i] += (char)1728; } } homecoming new string(chars); } }

i tried targeting numbers in innertext, did not work. code below changes tag numbers well.

private void loadhtmlfile(object sender, eventargs e) { var htmlfile = "<html><body><h1>i born in 1988</h1></body></html>" ; webbrowser1.documenttext=htmlfile; } private void webbrowser1_documentcompleted(object sender, webbrowserdocumentcompletedeventargs e) { webbrowser1.document.body.innertext = webbrowser1.document.body.innertext.toarabicnumber(); }

any suggestions?

you can utilize regular look find parts of html between '>' , '<' characters, , operate on those. prevent code processing tag names , attributes (style, etc).

// convert english language digits in string standard arabic digit equivalents public static string toarabicnums(string src) { const string digits = "۰۱۲۳۴۵۶۷۸۹"; homecoming string.join("", src.select(c => c >= '0' && c <= '9' ? digits[((int)c - (int)'0')] : c) ); } // convert english language digits in text segments of html // document standard arabic digit equivalents public static string toarabicnumshtml(string src) { string res = src; regex re = new regex(@">(.*?)<"); // regex matches matchcollection matches = re.matches(res); // process in reverse in case transformation function returns // string of different length (int = matches.count - 1; >= 0; --i) { match nxt = matches[i]; if (nxt.groups.count == 2 && nxt.groups[1].length > 0) { grouping g = nxt.groups[1]; res = res.substring(0, g.index) + toarabicnums(g.value) + res.substring(g.index + g.length); } homecoming res; }

this isn't perfect, since doesn't check @ html character specifiers outside of tags, such build &#<digits>; (&#1777; ۱, etc)to specify character unicode value, , replace digits in these. won't process text before first tag or after lastly tag.

sample:

calling: toarabicnumshtml("<html><body><h1>i born in 1988</h1></body></html>") result: "<html><body><h1>i born in ۱۹۸۸</h1></body></html>"

use whatever code prefer in toarabicnums actual transformation, or generalize passing in transformation function.

javascript converter arabic digits

No comments:

Post a Comment