Code Premix

Automatically set text direction based on input text language in JavaScript

📅June 12, 2022|🗁JavaScript

Today we’ll show you how we can automatically set text direction based on input text language in JavaScript.

When we type Arabic in the input field, which is written right-to-left (RTL), and when we start typing in English, it automatically changes to left-to-right (LTR). So in this article, we will see how to set text directions automatically.

In HTML5 you can simply do this by using dir="auto".

<input type="text" dir="auto">

It will automatically change the direction of the input base on the first character.

Note: It’s not supported in IE 11.

Alternative Solution

In this solution, we will use the CSS direction property to achieve this.

input {
  direction: rtl;
}

Here, we will use the regular expression to set the direction.

$('input').keyup(function () {
  $this = $(this);
  if ($this.val().length == 1) {
    var x = new RegExp("[\x00-\x80]+"); // is ascii
    var isAscii = x.test($this.val());

    if (isAscii) {
      $this.css("direction", "ltr");
    }
    else {
      $this.css("direction", "rtl");
    }
  }
});

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!