如何知道字符串在jQuery中以特定字符串开始/结束?

2022-08-30 01:08:19

我想知道字符串是以指定的字符/字符串开头还是以jQuery中的字符串结尾。

例如:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

如果没有任何功能,那么任何替代方案?


答案 1

一种选择是使用正则表达式:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}

答案 2

对于 startswith,您可以使用 indexOf:

if(str.indexOf('Hello') == 0) {

...

裁判

您可以根据字符串长度进行数学运算,以确定“endwith”。

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {