# isRTL.coffee library to determine if a text is of right-to-left direction

I just wrote this tiny library called isRTL.coffee to determine the direction of the text. Is there any better way of doing this?

rtlChars = '\u0600-\u06FF' # Arabic - Range

rtlChars += '\u0750-\u077F' # Arabic Supplement - Range

rtlChars += '\uFB50-\uFDFF' # Arabic Presentation Forms-A - Range

rtlChars += '\uFE70-\uFEFF' # Arabic Presentation Forms-B - Range

reRTL = new RegExp "^[#{rtlChars}]"

window.isRTL = (value) ->
if value.match reRTL
true
else
false


Yep, it's possible to improve. You can simply do:

window.isRTL = (value) ->
reRTL.test value


Another way to improve is the way you declare your special characters. Right now, it's confusing between the = and +=. Here is another way:

rtlChars = [
'\u0600-\u06FF' # Arabic - Range
'\u0750-\u077F' # Arabic Supplement - Range
'\uFB50-\uFDFF' # Arabic Presentation Forms-A - Range
'\uFE70-\uFEFF' # Arabic Presentation Forms-B - Range
].join("")

reRTL = new RegExp "^[#{rtlChars}]"


This way, adding a new character is simply adding a line in an array.

• @FlorianMargaine, using match is not appropriate, not only you are discarding the match but the function will not return a boolean value, so isRTL(...) === true will never evaluates to true. It would be best to use reRTL.test value instead. – plalx Oct 11 '13 at 6:38
• @plalx : Correction a string does not have a "test" method. match seems to be the way to go. – dhilipsiva Nov 28 '13 at 12:02
• @dhilipsiva No, just call test on the regular RegExp instance rather than the string like I demonstrated in my previous comment. – plalx Nov 28 '13 at 13:31
• @plalx I just feel so stupid sometimes :P Thanks. :) – dhilipsiva Nov 29 '13 at 12:31

The real usefulness of such a library can only come from completeness. You should try to support all other RTL languages as well. Anybody can come up with a simple function to detect Arabic chars.

Also, what if the text contains a mix of languages, some RTL while others LTR. Your library would report any text containing at least one arabic character as RTL.

• One approach would be to report number of RTL chars v/s LTR chars.
• Another take would be to parse the text into sections, each labeled as RTL or LTR.
• Removed the code samples, concentrating of the general talk. – Rene Saarsoo Oct 2 '13 at 13:00
• Yes, I agree. Just scratching my own itch for now. Will make it better eventually. :) – dhilipsiva Oct 2 '13 at 13:02