下面的对ES 6的处理字符串常用方法的整理,希望可以帮助到有需要的小伙伴,跟小编一起来看看吧~
includes()方法
includes()方法用于判断一个字符串是否包含在另一个字符串中,返回布尔值。
str.includes(searchString[,position])
- seacchStcing:在str字符串中搜索的字符串。
- position:可选项。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0.
注意:include()方法区分大小写
let str = "wolongxueyuan";
/*
ES5提供判断是否包含的方法
string.indexOf(searchStr)方法
* 作用 - 返回指定字符串中包含指定子字符串第一个匹配的索引值
* 结果
* 包含 - 返回第一个匹配的索引值
* 不包含 - 返回-1
*/
console.log(str.indexOf('o')); // 1
// 作用 - 返回指定字符串中包含指定子字符串最后一个匹配的索引值
console.log(str.lastIndexOf('o')); // 3
// ES6提供的include方法
console.log(str.includes('o'));
console.log(str.includes('o',3)) // 从索引值为3的地方开始查找
console.log(str.includes('o',5)); // false 从索引值为5的地方开始查找
// includes()方法是区别大小写的
console.log(str.includes('O')); // false
// 基于includes()方法实现一个不区分大小写的判断 - 把字符串都改成小写
// myIncludes()是全局方法
function myIncludes(str,searchStr,index){
// toLowerCase() 转为小写的方法
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
if (typeof index === 'number') {
return str.includes(searchStr,index)
} else {
return str.includes(searchStr);
}
}
console.log(myIncludes(str,'o')); // true
// return str.includes(searchStr,index);
// myIncludes()是string字符串对象里面的方法
/*Object.defineProperty(String.prototype, {
myIncludes : function (searchStr,index) {
let str = this.toLowerCase(); // this指针之心爱国String
searchStr = searchStr.toLowerCase();
if (typeof index==='number') {
return str.includes(searchStr,index);
}else {
return str.includes(searchStr);
}
}
});*/
startsWith()方法
startsWidth()方法用于判断某字符串 是否 是 指定字符串的指定索引值的开头字符串,如果不写索引值的化,索引值默认是0. 返回布尔值。
str.startsWith(searchString[, position])
- searchString:在 str.字符串中搜索的字符串。
- position:可选项。从当前字符串的哪个索引位置开始搜寻子字符串,默认值为0。
注意:
startsWidth()方法是区分大小写的
实例:
let str = "wolongxueyuan";
console.log(str.startsWith('wo'))
/*
startsWith()方法表示指定字符串的指定索引值开始是否以另一个字符串开始的
*/
// 指定字符串str的索引值为2的开头字符串
console.log(str.startsWith('long',2)); // true
endsWidth()方法
endsWidth()方法用于判断某字符串 是否 是 指定字符串的指定索引值的结尾字符串,如果不写索引值的化,从前向后数其索引值默认是1, 返回布尔值。
注意:
endsWidth()方法是区分大小写的
// endsWidth()方法用于判断某字符串 是否 是 指定字符串的指定索引值的结尾字符串,如果不写索引值的化,从前向后数其索引值默认是1
var str1 = "abcdefg";
console.log(str1.endsWith("a",1)); // true
console.log(str1.endsWith("de",5)); // true 从1开始,索引值为5的字母是e,以e的结尾字符串都是true
console.log(str1.endsWith("g",7)); // true 从1开始,索引值为7的字母是g,以g结尾的字符串都是true
注意:
ES6中 includes()方法、startsWith()方法、endsWidth()方法都是区分大小写的,如果不想区分大小写,可以将字符串都改成小写。
end~
本篇博客到这里就结束啦~