如何将用户(此处为用户名)的输入与子字符串数组进行比较并在同一页面的标签中产生输出?

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

我想要 javascript 中的代码。
我在 HTML5 中有一个输入字段,用户在其中输入他的名字并根据条件:

  1. 必须将他名字的前 3 个字母与字符串数组("Chu, Che, Cho, La,Lee, Lu, Le, Lo,A, E, U, Ea")等进行比较
  2. 如果他名字的第一个字母与上述数组变量中的任何一个匹配,则相应的消息应该打印在同一页中。

例如
用户名:奥斯汀

应该在'AUSTIN'中考虑"A",并根据匹配的场景显示消息。

if(chu,che,cho,la) 表示用户名属于 "Category1"
if(Lee,lu,le,lo) 表示用户名属于 "Category 2"
if(A,E,U,EA) 表示用户名属于“类别 3

如果用户输入用户名并按下提交按钮,结果必须显示在同一页面的某些标签或文本框中。

下次此代码将执行您需要它执行的操作:SO 不是一个您可以只索取代码并期望有人制作它的地方。

var letters = ["Chu", "Che", "Cho", "La", "Lee", "Lu", "Le", "Lo", "A", "E", "U", "Ea"];
var nameToCheck = "Austin";

//StartsWith function
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

//Function to get category
function check(name){
    for(var i=0; i<letters.length; i++){
        if(name.startsWith(letters[i])){
            if(letters[i] == "Chu" || letters[i] == "Che" || letters[i] == "cho" || letters[i] == "la") return name + " is Catogory 1";
            if(letters[i] == "Lee" || letters[i] == "Lu" || letters[i] == "Le" || letters[i] == "Lo") return name + " is Catogory 2";
            if(letters[i] == "A" || letters[i] == "E" || letters[i] == "U" || letters[i] == "Ea") return name + " is Catogory 3";
        }
    }
}

console.debug(check(nameToCheck));//will output "Austin is Catogory 3"

你应该使用正则表达式来检查。 这是一个正则表达式的例子:

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>
您可以在此处找到有关正则表达式的更多信息:http://www.w3schools.com/js/js_regexp.asp