一、子串的识别
- ES6 之前判断字符串是否包含子串,用 indexOf 方法,ES6 新增了子串的识别方法。
(1)includes():返回布尔值,判断是否找到参数字符串。
(2)startsWith():返回布尔值,判断参数字符串是否在原字符串的头部。
(3)endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部。
let str= "abcdefg abc";
console.log(str.includes("abc"));
console.log(str.startsWith("a"));
console.log(str.startsWith("a",8));
console.log(str.endsWith("fg"));
console.log(str.startsWith("g", 6));
- 注:这三个方法只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf 。
- 这三个方法如果传入了正则表达式而不是字符串,会抛出错误。而 indexOf 和 lastIndexOf 这两个方法,它们会将正则表达式转换为字符串并搜索它。
二、字符串重复–repeat()
- repeat():返回新的字符串,表示将字符串重复指定次数返回。
console.log("Hello".repeat(2));
console.log("Hello".repeat(3.2));
- 如果参数是 0 至 -1 之间的小数,会进行取整运算,0 至 -1 之间的小数取整得到 -0 ,等同于 repeat 零次
console.log("Hello,".repeat(-0.5));
console.log("Hello,".repeat(NaN));
console.log("Hello,".repeat(-1));
console.log("Hello,".repeat(Infinity));
console.log("Hello".repeat("hh"));
console.log("Hello".repeat(true));
console.log("Hello".repeat(false));
三、字符串补全
(1)padStart:返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串。
(1)padEnd:返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串。
- 以上两个方法接受两个参数,第一个参数是指定生成的字符串的最小长度,第二个参数是用来补全的字符串。如果没有指定第二个参数,默认用空格填充。
console.log("z".padStart(5, "o"));
console.log("z".padEnd(5, "o"));
console.log("z".padStart(5));
- 如果指定的长度小于或者等于原字符串的长度,则返回原字符串
console.log("hello".padStart(5, 'a'));
- 如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串
console.log("hello ".padEnd(10, 'world'));
console.log("123".padStart(10,"0"));
四、String.fromCodePoint()
- ES5 提供String.fromCharCode()方法,用于从 Unicode 码点返回对应字符,但是这个方法不能识别码点大于0xFFFF的字符。
- ES6 提供了String.fromCodePoint()方法,可以识别大于0xFFFF的字符,弥补了String.fromCharCode()方法的不足。在作用上,正好与codePointAt()方法相反。
- 如果String.fromCodePoint方法有多个参数,则它们会被合并成一个字符串返回。
- 注意,fromCodePoint方法定义在String对象上,而codePointAt方法定义在字符串的实例对象上。
let s = "\uD842\uDFB7";
console.log(s);
let str = "a";
let s1 = str.charCodeAt(0).toString(16);
console.log(String.fromCharCode(61));
console.log('\u0061');
console.log(String.fromCodePoint(0x6211));
console.log('\u6211');
五、codePointAt()
- ES6 提供了codePointAt()方法,能够正确处理 4 个字节储存的字符,返回一个字符的码点。
- codePointAt()方法是测试一个字符由两个字节还是由四个字节组成的最简单方法。
for(let char of str){
console.log(char.charCodeAt(0).toString(16));
}
console.log('我'.charCodeAt(0).toString(16));
六、trimStart()和trimEnd()
- trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。
var str = ' a b c ';
console.log(str.trim().length);
console.log(str.trimStart());
console.log(str.trimEnd());
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e44967207d14170e75032abf8d4dfc30.png)