微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ES6字符串包含方法

ECMAScript6增加了3个用于判断字符串是否包含另一个字符串的方法:startsWith()、endsWith()和includes()。

let message = "foobarbaz";
console.log(message.startsWith("foo")); // true
console.log(message.startsWith("bar")); // false
console.log(message.endsWith("baz")); // true
console.log(message.endsWith("bar")); // false
console.log(message.includes("bar")); // true
console.log(message.includes("qux")); // false

startsWith() 和 includes() 方法接收可选的第二个参数,表示
开始搜索的位置。如果传入第二个参数,则意味着这两个方法会从指定
位置向着字符串末尾搜索,忽略该位置之前的所有字符。下面是一个
子:

let message = "foobarbaz";
console.log(message.startsWith("foo")); //true
console.log(message.startsWith("foo", 1)); //false
console.log(message.includes("bar")); //true
console.log(message.includes("bar", 4)); //false
console.log(message.startsWith("bar", 3));// true

endsWith() 方法接收可选的第二个参数,表示应该当作字符串末尾
的位置。如果不提供这个参数,那么认就是字符串长度。如果提供这
个参数,那么就好像字符串只有那么多字符一样:

let message = "foobarbaz";
console.log(message.endsWith("bar")); //false
console.log(message.endsWith("bar", 6)); // true

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐