Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect user input language javascript

Is there a way to detect in which language user is typing in input/textarea field? I have seen such on facebook, If user starts typing in RTL language then cursor move on right side of input box. I tried to find but coould not see any idea, Thanks for any help

like image 884
user969068 Avatar asked May 01 '13 14:05

user969068


2 Answers

https://stackoverflow.com/a/14824756/104380

I had come up with a new, much shorter solution:

function isRTL(s){           
    var ltrChars    = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF'+'\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
        rtlChars    = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
        rtlDirCheck = new RegExp('^[^'+ltrChars+']*['+rtlChars+']');

    return rtlDirCheck.test(s);
};

playground page

like image 121
vsync Avatar answered Nov 01 '22 01:11

vsync


<input type="txt" id="give_lang"></br>
<button onclick='lngtype()'>Language</button>
<div id="lang_her">0</div>

<script type="text/javascript">

  function lngtype(text) {
  var text = document.getElementById("give_lang").value.replace(/\s/g); //read input value, and remove "space" by replace \s 
  //Dictionary for Unicode range of the languages
  var langdic = {
    "arabic" : /[\u0600-\u06FF]/,
    "persian" : /[\u0750-\u077F]/,
    "Hebrew" : /[\u0590-\u05FF]/,
    "Syriac" : /[\u0700-\u074F]/,
    "Bengali" : /[\u0980-\u09FF]/,
    "Ethiopic" : /[\u1200-\u137F]/,
    "Greek and Coptic" : /[\u0370-\u03FF]/,
    "Georgian" : /[\u10A0-\u10FF]/,
    "Thai" : /[\u0E00-\u0E7F]/,
    "english" : /^[a-zA-Z]+$/
      //add other languages her
  }  
  //const keys = Object.keys(langdic); //read  keys
  //const keys = Object.values(langdic); //read  values
  const keys = Object.entries(langdic); // read  keys and values from the dictionary
  Object.entries(langdic).forEach(([key, value]) => {  // loop to read all the dictionary items if not true
    if (value.test(text) == true){   //Check Unicode to see which one is true
      return document.getElementById("lang_her").innerHTML = key; //print language name if unicode true   
    }
  });
  }
</script>
like image 29
silver Avatar answered Nov 01 '22 00:11

silver