Skip to content

Instantly share code, notes, and snippets.

@nekofar
Created April 1, 2023 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekofar/f1f7b4f55e5ea24e49df289b034197a2 to your computer and use it in GitHub Desktop.
Save nekofar/f1f7b4f55e5ea24e49df289b034197a2 to your computer and use it in GitHub Desktop.
To determine if a text is in an RTL or LTR language, you can analyze the text's Unicode character set.
function getTextDirection(text) {
// Regular expression to match RTL Unicode characters
var rtlChars = /[\u0600-\u06FF\u0750-\u077F\u0590-\u05FF\u08A0-\u08FF\uFB50-\uFDCF\uFDF0-\uFDFF\uFE70-\uFEFF]/;
// Regular expression to match LTR Unicode characters
var ltrChars = /[\u0000-\u05FF\u0700-\u08FF\uFB00-\uFB4F\uFB50-\uFDFF\uFE70-\uFEFF]/;
// Count the number of RTL and LTR characters in the text
var rtlCount = (text.match(rtlChars) || []).length;
var ltrCount = (text.match(ltrChars) || []).length;
// Return the text direction based on the character count
if (rtlCount > 0 && ltrCount === 0) {
return 'rtl';
} else if (ltrCount > 0 && rtlCount === 0) {
return 'ltr';
} else {
return 'auto';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment