Judgment method: 1. Use the statement "String object.substr(0, number of comparison characters) == "Comparison characters""; 2. Use "String object.slice(0, characters number)=="Compare Characters"" statement; 3. Use the "String Object.indexOf("Compare Characters")==0" statement; 4. Use regular expressions.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript determines what the string begins with
Method 1: substr() method
if("123".substr(0, 2) == "12"){ console.log(true); }
Method 2: slice() method
if("123".slice(0,2) == "12"){ console.log(true); }
Method 3: indexOf() method
if("123".indexOf("12") == 0) { console.log(true); }
Method 4: Regular
if("123".search("12") != -1) { console.log(true); }if(new RegExp("^12.*$").test(12)) { console.log(true); }if("12".match(new RegExp("^12.*$"))) { console.log(true); }
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine what a string starts with in javascript. For more information, please follow other related articles on the PHP Chinese website!