HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

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

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
leftdirectiontextisrtlcoffeedeterminelibraryright

Problem

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

Solution

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.

Code Snippets

window.isRTL = (value) ->
    reRTL.test value
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}]"

Context

StackExchange Code Review Q#32131, answer score: 5

Revisions (0)

No revisions yet.