5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – plalx Oct 11 '13 at 6:38
  • \$\begingroup\$ @plalx : Correction a string does not have a "test" method. match seems to be the way to go. \$\endgroup\$ – dhilipsiva Nov 28 '13 at 12:02
  • \$\begingroup\$ @dhilipsiva No, just call test on the regular RegExp instance rather than the string like I demonstrated in my previous comment. \$\endgroup\$ – plalx Nov 28 '13 at 13:31
  • \$\begingroup\$ @plalx I just feel so stupid sometimes :P Thanks. :) \$\endgroup\$ – dhilipsiva Nov 29 '13 at 12:31
3
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ Removed the code samples, concentrating of the general talk. \$\endgroup\$ – Rene Saarsoo Oct 2 '13 at 13:00
  • \$\begingroup\$ Yes, I agree. Just scratching my own itch for now. Will make it better eventually. :) \$\endgroup\$ – dhilipsiva Oct 2 '13 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.