如何在JavaScript中检查字符串是否以另一个字符串开头
程序员文章站
2023-12-21 17:21:04
...
ES6, introduced in 2015, added the startsWith()
method to the String object prototype.
2015年推出的ES6向String对象原型添加了startsWith()
方法。
This is the way to perform this check in modern JavaScript
这是在现代JavaScript中执行此检查的方法
This means you can call startsWith()
on any string, provide a substring, and check if the result returns true
or false
:
这意味着您可以在任何字符串上调用startsWith()
,提供一个子字符串,并检查结果是否返回true
或false
:
'testing'.startsWith('test') //true
'going on testing'.startsWith('test') //false
This method accepts a second parameter, which lets you specify at which character you want to start checking:
此方法接受第二个参数,该参数可让您指定要开始检查的字符:
'testing'.startsWith('test', 2) //false
'going on testing'.startsWith('test', 9) //true
翻译自: https://flaviocopes.com/how-to-check-string-starts-with/