简体   繁体   English

如何检查字符串是否以数字开头并且在javascript中不包含任何substring?

[英]How to check if string starts with number and does not contain any substring with it in javascript?

I want to check if the first element of the string is number and if it is number then there should not be any word attached with this number.我想检查字符串的第一个元素是否是数字,如果它是数字,那么这个数字不应该附加任何单词。 Following is an example to make it clear:下面举例说明:

function startsWithNumber(str) {
  return /^\d/.test(str);
}

// Actual Output
console.log(startsWithNumber('123avocado')); // 👉️ true
console.log(startsWithNumber('123 avocado')); // 👉️ true

// Required Output
console.log(startsWithNumber('123avocado')); // 👉️ false
console.log(startsWithNumber('123 avocado')); // 👉️ true
  

Required output explains that although string is starting with number but it contains word avocado attached to it without any space, which should give false as an output. Any help would be much appreciated.必需的 output 解释说,虽然字符串以数字开头,但它包含单词avocado ,没有任何空格,这应该给出false的 output。任何帮助将不胜感激。

You can use the the positive lookahead operator to check if there is either a space or end of the string after X amount of numbers.您可以使用正先行运算符来检查 X 个数字后是否有空格或字符串结尾。 This should work:这应该工作:

 function startsWithNumber(str) { return /^\d+(?=\s|$)/.test(str); } console.log(startsWithNumber('123avocado')); // ️ false console.log(startsWithNumber('123 avocado')); // ️ true

\s matches a space and $ matches end of string. \s 匹配空格,$ 匹配字符串结尾。

If the number should not be followed by a word character you can use a word boundary:如果数字后面不应跟单词字符,则可以使用单词边界:

^\d+\b

Regex demo正则表达式演示

Or assert a whitespace boundary to the right:或者断言右侧的空白边界:

^\d+(?!\S)

Regex demo正则表达式演示

 function startsWithNumber(str) { return /^\d+\b/.test(str); } console.log(startsWithNumber('123avocado')); // ️ false console.log(startsWithNumber('123 avocado')); // ️ true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM