检查一个字符串(str
)是否以指定的字符串(target
)结尾。
如果是,返回true;如果不是,返回false。
function confirmEnding(str, target) {
return(str.substr(str.length - target.length, target.length) === target);
// return str.endsWith(target);//方法二
}
confirmEnding("Bastian", "n");
substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。
stringObject.substr(start,length)
参数 | 描述 |
---|---|
start | 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。 |
length | 可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。 |
endsWith()
方法确定字符串是否以指定字符串的字符结尾,返回true
或false
适当。
例子:
const str1 = 'Cats are the best!';
console.log(str1.endsWith('best', 16));
// expected output: true
const str2 = 'Is this a question';
console.log(str2.endsWith('?'));
// expected output: false
测试用例:
confirmEnding("Bastian", "n")
应该返回 true.
confirmEnding("Connor", "n")
应该返回 false.
confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")
应该返回 false.
confirmEnding("He has to give me a new name", "name")
应该返回 true.
confirmEnding("He has to give me a new name", "me")
应该返回 true.
confirmEnding("He has to give me a new name", "na")
应该返回 false.
confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")
应该返回 false.