Martin AJ Martin AJ - 3 months ago 15
CSS Question

How can I change the direction of textarea when there is Persian character?

Here is my code:



$("body").on('input', 'textarea', function() {

var el = $(this);
var len = el.val().length;

if (len <= 1){
var x = new RegExp("[A-Za-z]"); // is ascii
var isAscii = x.test(el.val().substring(0, 1));
if(isAscii){
el.css("direction", "ltr");
} else {
el.css("direction", "rtl");
}
}

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>dynamic direction</textarea>





My current code changes the direction of such a textarea. It is based on the first character:


  • If the first character is either a Persian character or a sign, it sets
    rlt
    direction to that textarea.

  • If the first character is a English character, it sets
    lrt
    direction to that textarea.



Well that's not what I want. I want this:


  • If the first letter (not signs) is a English letter, then set the textarea
    ltr
    direction. Otherwise set it
    rtl
    .






Here is some examples:

var test = "..!"; // rtl
var test = "te"; // ltr
var test = "!te"; // ltr
var test = "..ق"; // rtl
var test = "مب"; // rtl
var test = "eس"; // ltr
var test = "سe"; // rtl
var test = "^سe"; // rtl
var test = ".32eس"; // ltr


How can I do that?

Answer

If I read the question correctly, the goal is to have the text read left-to-right if the first non-symbol/sign/punctuation character is an ASCII character, otherwise read right-to-left.

I think all you need to do is change your regex to first match 0 or more symbols/signs/punctuation-marks, and then to test if the next character is an ASCII character.

The regex [-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/] is a fairly complete regex for symbols/signs/punctuation-marks, found here: http://stackoverflow.com/a/8359631/4132627. You may need to add to it as you see fit.

Putting that together we'd get something like [-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]*[A-z]. The * between the two character groups means "match 0 or more of the previous group".

I've updated your snippet with that regex and it appears to work as expected. Also removed the length check as this needs to run no matter how many characters there are.

This probably isn't perfect - there are many cases probably being left out. You may need to play with it a bit. For example, should that second character group also include numbers ([A-z0-9])?

In any case, I hope this helps!

$("body").on('input', 'textarea', function() {
  
      var el  = $(this);
      var len = el.val().length;
  
      //if (len <= 1){
    	    var x = /^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]*[A-Za-z]/; // is ascii
  	  	    var isAscii = x.test(el.val());

		    if(isAscii){
		    	el.css("direction", "ltr");
		    } else {
		    	el.css("direction", "rtl");
	  	  }
    	//}
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>dynamic direction</textarea>