使用 JavaScript 检查 String 是否以 Number 开头

检查字符串是否以数字开头

Check if String starts with Number using JavaScript

要检查字符串是否以数字结尾,请test()在以下正则表达式 – 上调用该方法/^\d/如果字符串以数字开头,则test方法将返回,否则将返回。truefalse

索引.js
// ✅ 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
方法来检查字符串是否以数字结尾。

正斜杠/ /标记正则表达式的开始和结束。

插入符^匹配输入的开头。

The \d special character matches digits in the range of 0 to 9. Using the\d special character is the same as using a range like [0-9].

If you ever need help reading a regular expression, check this
regex cheatsheet
from MDN out.

In its entirety, the regular expression matches one or more digits at the
beginning of the string.

The second function we defined uses the
String.match
method.

Notice that we added a + at the end of the regex. The plus matches the preceding item (digits range) one or more times.

If the match method matches the regular expression in the string it returns an
array containing the matches.

If no matches are found, the method returns null.

在调用该方法之前,我们使用我们的startsWithNumber函数来验证是否存在匹配项。match

最后一步是将匹配的字符串转换为数字并返回结果。