在 ES6 中,JavaScript 新增了许多字符串扩展方法,如 includes、startsWith、endsWith 等。相比以前的 indexOf 等方法,这些新的方法不仅更加易读易用,还可以大大提高代码的简洁性和效率。
includes 方法
includes 方法用于判断一个字符串是否包含另一个字符串,它的语法如下:
str.includes(searchString[, position])
其中,searchString 为要搜索的字符串,position 为搜索的起始位置(可选,默认为 0)。如果能够找到 searchString,则返回 true,否则返回 false。
示例代码如下:
const str = 'Hello world'; console.log(str.includes('Hello')); // true console.log(str.includes('llo', 2)); // true console.log(str.includes('foo')); // false
startsWith 方法
startsWith 方法用于判断一个字符串是否以另一个字符串开头,它的语法如下:
str.startsWith(searchString[, position])
其中,searchString 为要搜索的字符串,position 为搜索的起始位置(可选,默认为 0)。如果字符串以 searchString 开头,则返回 true,否则返回 false。
示例代码如下:
const str = 'Hello world'; console.log(str.startsWith('Hello')); // true console.log(str.startsWith('lo', 3)); // true console.log(str.startsWith('foo')); // false
endsWith 方法
endsWith 方法用于判断一个字符串是否以另一个字符串结尾,它的语法如下:
str.endsWith(searchString[, length])
其中,searchString 为要搜索的字符串,length 为搜索的长度(可选,默认为 str.length)。如果字符串以 searchString 结尾,则返回 true,否则返回 false。
示例代码如下:
const str = 'Hello world'; console.log(str.endsWith('world')); // true console.log(str.endsWith('llo', 5)); // true console.log(str.endsWith('foo')); // false
repeat 方法
repeat 方法用于重复一个字符串,它的语法如下:
str.repeat(count)
其中,count 为重复的次数,必须是一个非负整数。如果 count 小于等于 0,则返回一个空字符串。
示例代码如下:
const str = 'Hello world'; console.log(str.repeat(3)); // 'Hello worldHello worldHello world'
指导意义
字符串扩展方法包括 includes、startsWith、endsWith 等,可以大大提升代码的可读性和效率。上述方法能够更直观地判断字符串的包含、开头和结尾,使用时应注意参数的设置和返回值的判断。
此外,在使用字符串时还应注意避免出现编码不规范、转义符不正确等问题,避免出现不必要的错误。
总结
在 ES6 中,字符串扩展方法包括 includes、startsWith、endsWith 等,它们可以大大提升代码的可读性和效率。在实际开发中,应注意使用方法的参数和返回值,并避免出现不规范的编码和转义符问题。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/645b4dde968c7c53b0da72e6