简体   繁体   中英

javascript tests if the entered character string starts with an alphabet

I want to test if a character string passed as a parameter starts with an uppercase or lowercase letter between 'a' and 'd'. I wrote this code but it doesn't work it always gives the content of else

 function controler1() { var x=document.getElementById("champ1").value; if (x.startsWith("a") || x.startsWith("b") || x.startsWith('c')|| x.startsWith('d')|| x.startsWith('A')|| x.startsWith('B')|| x.startsWith('C')|| x.startsWith('D')) { document.getElementById("teste1").innerHTML=x+" "+"chaine valide commence par une lettre entre a et d"; }else{ document.getElementById("teste1").innerHTML=x+" "+"chaine invalide ne commence pas par une lettre entre a et d"; } }
 <style type="text/css"> #la{border: 1px solid black; width: 800px;} </style> <div id="la"> <br> <input type="text" id="champ1" value=" "><br> <input type="button" value="tester" onclick="controler1()"> <p id="teste1"></p> </div>

It is because you have empty space prefixed to your input string because of -

 <input type="text" id="champ1" value=" ">

Change this to -

 <input type="text" id="champ1" value="">

You can use regex to avoid so many if conditions -

/^(a|b|c|d)/gi.test(input)

 function controler1() { var input = document.getElementById("champ1").value; var satisfies = /^(a|b|c|d)/gi.test(input); if (satisfies) { document.getElementById("teste1").innerHTML = input + " " + "chaine valide commence par une lettre entre a et d"; } else { document.getElementById("teste1").innerHTML = input + " " + "chaine invalide ne commence pas par une lettre entre a et d"; } }
 #la { border: 1px solid black; width: 800px; }
 <div id="la"> <br> <input type="text" id="champ1" value=""><br> <input type="button" value="tester" onclick="controler1()"> <p id="teste1"></p> </div>

My suggestion:

 champ1.oninput = () => { var res = /^(a|b|c|d)/gi.test(champ1.value); // case insensitive console.log('Starts with a/A, b/B, c/C or d/D: ' + res); }
 <input type="text" id="champ1">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM