EagleEye
EagleEye

Reputation: 508

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.

Upvotes: 0

Views: 397

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 2

Tyler Fretz
Tyler Fretz

Reputation: 46

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. 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.

Upvotes: 3

Related Questions