在 ECMAScript 2015 规范中,新增了一些字符串操作方法,同时对一些现有方法做了改进。这些改进和新增对前端开发具有非常重要的意义,可以大大提升开发效率和代码可读性。本文将对 ECMAScript 2015 中的字符串操作方法进行详细介绍和示例演示。
String.prototype.includes()
ECMAScript 2015 中新增了一个字符串操作方法 includes()
,可以用来判断一个字符串是否包含另一个字符串。
语法
str.includes(searchString[, position])
参数
- searchString:要查找的子字符串。
- position(可选):在字符串中搜索 searchString 的开始位置,默认值为 0。
返回值
如果字符串包含搜索字符串,返回 true
,否则返回 false
。
示例
const str = 'hello world'; console.log(str.includes('world')); // true console.log(str.includes('World')); // false console.log(str.includes('world', 6)); // false
String.prototype.startsWith()
startsWith()
方法用于判断当前字符串是否以指定字符串开头。
语法
str.startsWith(searchString[, position])
参数
- searchString:要查找的子字符串。
- position(可选):在字符串中搜索 searchString 的开始位置,默认值为 0。
返回值
如果当前字符串以指定字符串开头,返回 true
,否则返回 false
。
示例
const str = 'hello world'; console.log(str.startsWith('hello')); // true console.log(str.startsWith('Hello')); // false console.log(str.startsWith('world', 6)); // true
String.prototype.endsWith()
endsWith()
方法用于判断当前字符串是否以指定字符串结尾。
语法
str.endsWith(searchString[, length])
参数
- searchString:要查找的子字符串。
- length(可选):当前字符串需要检查的长度,如果不指定,则检查整个字符串。
返回值
如果当前字符串以指定字符串结尾,返回 true
,否则返回 false
。
示例
const str = 'hello world'; console.log(str.endsWith('world')); // true console.log(str.endsWith('World')); // false console.log(str.endsWith('hello', 5)); // true
String.prototype.repeat()
repeat()
方法用于复制指定字符串的指定次数。
语法
str.repeat(count)
参数
- count:需要复制的次数。必须是一个正整数。
返回值
返回被复制的字符串。
示例
console.log('hello'.repeat(3)); // hellohellohello console.log('2'.repeat(4)); // 2222
String.prototype.padStart() 和 String.prototype.padEnd()
padStart()
和 padEnd()
方法用于在当前字符串的开头或结尾填充指定的字符串,直到字符串达到指定的长度。
语法
str.padStart(targetLength [, padString]) str.padEnd(targetLength [, padString])
参数
- targetLength:当前字符串需要填充到的目标长度。必须是一个非负整数。
- padString:用于填充的字符串。如果不指定,则使用空格填充。
返回值
返回填充后的新字符串。
示例
console.log('hello'.padStart(10, 'x')); // xxxxxhello console.log('hello'.padEnd(10, 'x')); // helloxxxxx console.log('hello'.padStart(10)); // hello
消除 Unicode 操作困难的问题
在早期版本的 ECMAScript 中,处理 Unicode 字符通常是一个非常困难的任务。然而,在 ECMAScript 2015 中,新的字符串处理方式对于 Unicode 字符的处理非常友好,可以极大地简化开发者的工作。
示例
console.log('\u{20BB7}'); // output: "𠮷" console.log('\u{20BB7}'.length); // output: 2 console.log('\u{20BB7}'.charAt(0)); // output: ""
结论
在 ECMAScript 2015 中,新增和改进了一些字符串操作方法,这些方法可以极大地提升开发效率和代码可读性,尤其是对于处理 Unicode 字符的情况。了解和掌握这些方法可以让前端开发更加得心应手。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/670ccf125f551281025bbd48