Automatically set text direction based on input text language in 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.
- One-Liners JavaScript code that you should know
- How to add days to a date in JavaScript
- How to get first N elements of an array in JavaScript
- How to check whether a string contains a substring in JavaScript
- Validate the value by regular expression in JavaScript
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..!!