字符串的解耦赋值(详细讲解)

卓越的人一大优点是:在不利与艰难的遭遇里百折不挠。 ——贝多芬

判断当前字符串是否包含另外一个给定的子字符串

ES5 提供是否包含的方法
string.indexOf(searchStr) 方法
* 作用 - 返回指定字符串中包含指定子字符串的第一个匹配的索引值
* 结果 –
* 包含 - 返回第一个匹配的索引值
* 不包含 - 返回-1

console.log(str.indexOf('we', 3)); //5 //从指定位置开始往后查找
console.log(str.indexOf('we'));//1 //从整个字符串中查找

ES6提供是否包含的方法
includes ()方法

console.log(str.includes('we')); //true//从整个字符串中查找
console.log(str.includes('we', 3)); //true//从指定位置开始往后查找

判断当前字符串是否是以另外一个给定的子字符串“结尾”的

endswidth()方法

  • 判断是否以该索引值为终止点的字符串的结尾 返回值为布尔型
let str = 'swedrwefweda';
console.log(str.endsWith('da')); //true
console.log(str.endsWith('swe', 3)); //true

判断当前字符串是否是以另外一个给定的子字符串“给定”的

startswidth()方法

  • 不是表示指定字符串是以另一个字符串开始的
  • 表示指定字符串的指定索引值开始是否以另一个字符串开始的
  • 判断该字符串是否以指定索引值开始的字符串 是的话返回true 否则false
let str = 'swedrwefweda';
console.log(str.startsWith('sw')); //true
console.log(str.startsWith('dr', 3)); //false

在这里插入图片描述

上述的方法都是区分大小写的
因为咋们在工作中极有可能会遇到不想让她区分大小写所以我就写了一个例子(将其变为不区分大小写的)
可以让咋们工作效率一点点变快

let str = 'swedrwefweda';
Object.defineProperty(String.prototype, 'myIncludes', {
    value: function (searchStr, index) {
        let str = this.toLowerCase();
        searchStr = searchStr.toLowerCase();
        if (typeof index === 'number') {
            return str.includes(searchStr, index);
        } else {
            return str.includes(searchStr);
        }
    }
});
console.log(str.myIncludes('we', 3))

希望大家在工作中一点点积累 一点点进步哦

今日金句

不积跬步,无以至千里;不积小流,无以成江海。

猜你喜欢

转载自blog.csdn.net/weixin_50001396/article/details/111556297