9

guys i have a problem with this thing , i must know which language the user is using while typing in an input text to handle some bad shaped things and i even looked at this in here but it didn't helped me , can u guys help me with the right code ?
the languages i must know are english and persian :| thanks :) i need some javascript helps

<input type="text" id="give_me_the_lang">
<div id="show_lang_in_here"></div>
Community
  • 1
  • 1
user3590110
  • 113
  • 1
  • 1
  • 6
  • Do you want to detect the language the user is typing in? – surajck Jan 20 '15 at 09:49
  • yea , thats what i want – user3590110 Jan 20 '15 at 09:53
  • 2
    What makes you imperatively rely on detecting the language while the user is typing? There are browser extensions for spelling that would make this task on the client side pointless at best. Detecting a language is a really complex operation and to my knowledge only office suites support such a feature, which I sense to require heavy coding. Also, as far as I recall, their language detection is far from foolproof. –  Jan 20 '15 at 09:59
  • Yes. I agree. You can give a dropdown where the user can select which language he is going to write in. That way you would know. – surajck Jan 20 '15 at 10:00
  • the thing is user will type a mix lang , both rtl and ltr languages , so i need to know which One is typing to handle its shape , cause writing in ltr text with rtl will be the worst thing u wanna see in a site and vice versa – user3590110 Jan 20 '15 at 10:06
  • You could check if input contains special characters from persian language, and if so, show it rtl. Otherwise, show it ltr. – Crepi Jan 20 '15 at 10:09
  • thats what i wanna do , but im not goOd at js , i may need some kind of regex or something , that i dont know how to use them in js :| – user3590110 Jan 20 '15 at 10:15

2 Answers2

12

Here is the solution that doesn't really detect language, but just checks if users input contains only English alphabet. If it does, it writes "English" in div, otherwise it writes "Persian". Code:

document.getElementById("give_me_the_lang").addEventListener("keyup", function() {
  if (/^[a-zA-Z]+$/.test(this.value)) {
    document.getElementById("show_lang_in_here").innerHTML = "English";
  } else {
    document.getElementById("show_lang_in_here").innerHTML = "Persian";
  }
});
<input type="text" id="give_me_the_lang">
<div id="show_lang_in_here"></div>

Expression ^[a-zA-Z]+$ only checks the letters of English alphabet, if you write in number or any other character, the result will be "Persian".

Crepi
  • 645
  • 5
  • 15
  • tanx a lot m8 , i was after the other answers i was thinking about this solution , but i didnt know how in here :) , but there is a problem , if i start with persian and i go for english and then persian it works correctly but after that doesnt detect english , or if i start with english then persian it works , but after that if i go to english i doesnt work any further , if u solve this One 2 ill be glad :) and can u tell me Expressions for numbers 2 ? – user3590110 Jan 20 '15 at 12:16
  • 1
    This function checks whole input, and if it finds any Persian character, the result would be Persian. No matter in witch order you enter them. To include numbers change expression to: ^[a-zA-Z0-9]+$ – Crepi Jan 20 '15 at 12:26
  • how can i check just the last word ? wheter the last word is persian Or english – user3590110 Jan 20 '15 at 12:32
  • Inside the function add var words = this.value.split(" "); It creates array of words from input. And with words[words.length - 1] you get the last word witch you can check in if condition. Also, change regular expression to /^[a-zA-Z0-9 ]*$/ so it would include spaces and empty strings. – Crepi Jan 20 '15 at 12:44
  • OK than what about something like this. "سلام mike. حالت چطوره؟". The text in `show_lang_in_here` goes from "persian" to "english" and then "persian". There should be a deeper analysis if someone wants to detect a text language. – pouya Dec 27 '18 at 10:07
4

Detecting language is a task that a plain if else or switch case won't be able to solve... you got a computer learning problem to solve here my friend.

The good thing is, that there are already crazy geniuses out there that already solved your problem, so why don't use their available solution?

https://cloud.google.com/translate/v2/getting_started#language_detect

  1. Signup for the Google Cloud platform
  2. Activate the access to the Google Translate API
  3. Get a Browser access token for your API. You need this token in order to use it from JavaScript.
  4. Now wire up your UI and let them do the magic.

Your HTML will remain the same. Just make sure you also include jQuery.

<input type="text" id="give_me_the_lang" />
<div id="show_lang_in_here"></div>

Now lets wire up the UI

$(function(){

    /* We want to listen to the keypress events from the user 
    *  Each time the user stops typing we wait a few milliseconds and then
    *  we ask Google to detect the language for us */
    var timeoutID;

    /* Replace this with your Google Translate API key */
    var myKey = 'XXXX';

    var detectLanguage = function(){

        $.ajax({
            method: 'GET',
            url: 'https://www.googleapis.com/language/translate/v2/detect',
            data: {
               key: myKey,
               q: $('#give_me_the_lang').val()
            }           
        }).done(function(response){

           /* Push the response to the UI */
           $('#show_lang_in_here').text(JSON.stringify(response.data.detections));
        });        
    };

    $('#give_me_the_lang').on('keyup, keypress, change', function(){
        clearTimeout(timeoutID);

        /* Lets wait half a second */
        setTimeout(detectLanguage, 500);
    });
});

The thing to parse in the response is the array of detections that Google will send back.

{
    "data": {
       "detections": [
         [
           {
            "language": "de",
            "isReliable": false,
            "confidence": 0.049747143
           }
         ]
       ]
    }
}

Which is a perfect example of overly complicated computation result... so, I would say, if the guy gives you one guess, use it, if the guy gives you more, the pick the one you think is the most approximate for your user base (you don;t have customers in North Korea or in Bolivian Quechua territory do you?)

Adrian Salazar
  • 5,279
  • 34
  • 51