JavaScript 中检查字符串是否以指定的子字符串开头
要检查字符串是否以子字符串开头,请对字符串调用 startsWith() 方法,并将子字符串作为参数传递给它。 如果字符串以子字符串开头,则 startsWith 方法返回 true,否则返回 false。
const str = 'hello world';
if (str.startsWith('hello')) {
// ?️ this runs
console.log('✅ string starts with hello');
} else {
console.log('⛔️ string does NOT start with hello');
}
我们使用 String.startsWith 方法来确定字符串是否以特定子字符串开头。
该方法返回一个布尔结果:
- 如果字符串以子字符串开头,则为真
- 如果没有则为假
const str = 'HELLO world';
const substr = 'hello';
if (str.toLowerCase().startsWith(substr.toLowerCase())) {
// ?️ this runs
console.log('✅ string starts with hello');
} else {
console.log('⛔️ string does NOT start with hello');
}
使用 indexOf 检查 String 是否以 Substring 开头
要检查字符串是否以子字符串开头,请对字符串调用 indexOf() 方法,将子字符串作为参数传递给它。 如果 indexOf 方法返回 0,则字符串以子字符串开始,否则不是。
const str = 'hello world';
const substr = 'hello';
if (str.indexOf('hello') === 0) {
// ?️ this runs
console.log('✅ string starts with hello');
} else {
console.log('⛔️ string does NOT start with hello');
}
如果子字符串不包含在字符串中,则返回 -1。
如果该方法返回 0,我们可以断定该字符串以子字符串开头。
使用 Regex 检查字符串是否以指定的子字符串开头
要检查字符串是否以子字符串开头,请使用 test() 方法和匹配字符串开头的子字符串的正则表达式。 如果字符串以子字符串开头,测试方法将返回 true,否则返回 false。
if (/^abc/.test('abc123')) {
// ?️ this runs
console.log('✅ string starts with abc');
} else {
console.log('⛔️ string does NOT start with abc');
}
我们使用 RegExp.test 方法检查字符串是否以特定子字符串开头。
如果正则表达式在字符串中匹配,则该方法返回 true,否则返回 false。
在此示例中,我们检查字符串 abc123 是否以子字符串 abc 开头。
如果在阅读正则表达式时需要帮助,请查看我们的正则表达式教程。
// ?️ with `i` flag
if (/^abc/i.test('ABC123')) {
// ?️ this runs
console.log('✅ string starts with abc');
} else {
console.log('⛔️ string does NOT start with abc');
}
i 标志允许我们在字符串中执行不区分大小写的搜索。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。