如何检查以某些给定字符/pattern 开头的字符串?
我们可以通过javascript中的各种方法检查给定的字符串是否以指定字符串的字符开头,如下所述:
方法1:这是一种简单的方法,我们将从使用循环开始逐个匹配字符,如果任何字符不匹配,那么我们可以说字符串不以字符或指定字符串开头。
句法:
for (var i = 0; i < pattern.length; i++) {
if(str.charAt(i) != pattern.charAt(i)){
result = false;
break;
}
}
示例:下面的程序演示了上述方法:
输出:
String = "GeeksforGeeks"
String should begin with = "Geeks"
String begins with "Geeks"
String = "geeksforgeeks"
String should begin with = "Geeks"
String doesn't begins with "Geeks"
方法二:在这个方法中,我们将使用 substring()函数获取所需长度的模式字符串的子字符串,然后使用 localeCompare()函数将子字符串与模式匹配。
句法:
var = string.substring(Startindex, Endindex)
var.localeCompare(compareString)
示例:下面的程序演示了上述方法:
输出:
String = "GeeksforGeeks"
String should begin with = "Geeks"
String begins with "Geeks"
String = "geeksforgeeks"
String should begin with = "Geeks"
String doesn't begins with "Geeks"
方法3:这是最好的解决方案,在这个方法中我们将使用startsWith()方法直接检查给定的字符串是否以某物开头。
句法:
str.startsWith( searchString , position )
示例:下面的程序演示了上述方法:
输出:
String = "Burn to shine"
String should begin with = "Burn"
String begins with "Burn"
String = "Happy coding"
String should begin with = "happy"
String doesn't begins with "happy"