JavaScript 中检查字符串是否以数字开头
要检查字符串是否以数字结尾,请对以下正则表达式调用 test()
方法 - /^\d/
。 如果字符串以数字开头,测试方法将返回 true,否则将返回 false。
// ✅ Check if string starts with number ✅
function startsWithNumber(str) {
return /^\d/.test(str);
}
console.log(startsWithNumber('avocado 123')); // 👉️ false
console.log(startsWithNumber('123 avocado')); // 👉️ true
console.log(startsWithNumber('0.5 test')); // 👉️ true
// ✅️ Get number from start of string ✅
function getNumberAtEnd(str) {
if (startsWithNumber(str)) {
return Number(str.match(/^\d+/)[0]);
}
return null;
}
console.log(getNumberAtEnd('avocado 123')); // 👉️ null
console.log(getNumberAtEnd('123 avocado')); // 👉️ 123
console.log(getNumberAtEnd('0.5 test')); // 👉️ 0
我们使用 RegExp.test
方法来检查字符串是否以数字结尾。
正斜杠
//
标记正则表达式的开始和结束。插入符号^
匹配输入的开头。
\d
特殊字符匹配 0 到 9 范围内的数字。使用\d
特殊字符与使用范围 [0-9] 相同。
如果在阅读正则表达式时需要帮助,请查看我们的正则表达式教程。
就其整体而言,正则表达式匹配字符串开头的一个或多个数字。
我们定义的第二个函数使用 String.match 方法。
请注意
,我们在正则表达式的末尾添加了一个+
。 加号与前面的项目(数字范围)匹配一次或多次。
如果 match 方法匹配字符串中的正则表达式,它会返回一个包含匹配项的数组。
如果未找到匹配项,则该方法返回 null。
在调用 match 方法之前,我们使用
startsWithNumber
函数来验证是否存在匹配项。
最后一步是将匹配的字符串转换为数字并返回结果。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。