如何在JavaScript中检查一个字符串是否以另一个字符串开头

如何在JavaScript中检查一个字符串是否以另一个字符串开头

在JavaScript中, ‘startsWith()’ 方法是一种内置方法,允许我们检查一个字符串是否以指定的子字符串开头。

语法: 它接受一个参数,即我们想要检查字符串是否以其开头的子字符串。

string.startsWith(searchString[, position])

步骤: ‘searchString’ 参数是要在字符串开头搜索的子字符串。 ‘position’ 参数是一个可选参数,指定开始搜索的字符串位置。如果未指定,则从字符串开头(位置0)开始搜索。

示例1: 这个示例展示了上述步骤的使用。

const str = 'Hello Geeks!';
  
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('Geeks', 6)); // true
console.log(str.startsWith('Geeks', 7)); // false

输出:

true
true
false

示例2: 这个示例展示了上述步骤的使用。

var x ="Hello World!"
function myfunc() {
    if (x.startsWith('Hello')) {
        result = true;
    } else {
        result = false;
    }
console.log(result);
}
myfunc();

输出:

true

阅读更多:JavaScript 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程