Search code examples
javascriptarraysstringhtmldynamic-arrays

How to compare the input of user(here username) to the array of substrings and produce output in a label of same page?


I want a code in javascript.
I have an input field in HTML5 and user enters his name in it and as per condition:

  1. The first 3 letters of his name has to be compared with an array of strings like("Chu, Che, Cho, La,Lee, Lu, Le, Lo,A, E, U, Ea") etc.
  2. If the first letters of his name are matched with any one of above array variable then the corresponding message should be printed in the same page.

For Example
username : Austin

It should consider "A" in 'AUSTIN' and display message as per matched scenario.

if(chu,che,cho,la) means username belongs to "Category1"
if(Lee,lu,le,lo) means username belongs to "Category 2"
if(A,E,U,EA) means username belongs to "Category 3

If user enters his username and press submit button, result has to be displayed in some label or textbox of same page.


Solution

  • you should use regex to check. here is an example with regex:

    var doc = document,    
        result = doc.getElementById('result'),
        el = doc.getElementById('name'),
        but = doc.getElementsByTagName('button'),
        
        check = function(evt){
            //stop propagation
            evt.preventDefault();
            //value of input
            var dares=el.value;
            //regex
            var categ1=/^ch(u|o|e)/i;
            var categ2=/^l(u|o|ee|e)/i;
            var categ3=/^(A|E|U|EA)/;
            
            result.innerHTML="your name is <strong>"+dares+"</strong>.<br>And it ";
            if(categ1.test(dares)){
                result.innerHTML += "...matches <strong>categ1</strong>.";
            }else if(categ2.test(dares)){
                result.innerHTML += "... matches <strong>categ2</strong>.";
            }else if(categ3.test(dares)){
               result.innerHTML += "... matches <strong>categ3</strong>. ";
            }else{
                result.innerHTML += "... <strong>doesn't match</strong> any category.";
            }
            
        };
        
        but[0].addEventListener("click", check, false);
    <form action="" method="post">
        <input type="text" name="name" id="name" placeholder="your name"/>
        <button>Check</button>
    </form>
    <h3>Result</h3>
    <div id="result"></div>
    you can find more information about regex here: http://www.w3schools.com/js/js_regexp.asp