Home >Web Front-end >JS Tutorial >How to determine what a string starts with in javascript

How to determine what a string starts with in javascript

青灯夜游
青灯夜游Original
2021-10-09 17:12:1517340browse

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.

How to determine what a string starts with in javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn