includes(), startsWith(), endsWith()
- includes():返回布尔值,表示是否找到了参数字符串。
- startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
- endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
- 例如:
-
let s = 'Hello world!'; s.startsWith('Hello') // true s.endsWith('!') // true
这三个方法都支持第二个参数,表示开始搜索的位置。,例如:
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
repeat()
repeat方法返回一个新字符串,表示将原字符串重复n次。
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
参数如果是小数,会被取整。
'na'.repeat(2.9) // "nana"
如果repeat的参数是负数或者Infinity,会报错。
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
但是,如果参数是 0 到-1 之间的小数,则等同于 0,这是因为会先进行取整运算。0 到-1 之间的小数,取整以后等于-0,repeat视同为 0。
'na'.repeat(-0.9) // ""
本文详细介绍了JavaScript中字符串的includes(), startsWith(), endsWith()和repeat()方法的使用。includes()用于检查字符串是否包含特定子串,startsWith()和endsWith()分别用于判断字符串是否以特定子串开头或结尾,repeat()则用于重复字符串特定次数。
1084

被折叠的 条评论
为什么被折叠?



