Matheus Mello

Berlin, Germany

Check if String contains at least one Number in JavaScript

Cover Image for Check if String contains at least one Number in JavaScript
Matheus Mello
Matheus Mello

Check assuming that String contains Numbers #

Utilize the RegExp.test() strategy to check in the event that a string contains no less than one number, for example /\d/.test(str). The test strategy will return valid if the string contains no less than one number, generally bogus will be returned.
index.js

const str1 = 'hi 42 world';
const str2 = 'hi world';

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

console.log(containsNumber(str1));//👉️ valid
console.log(containsNumber(str2));//👉️ bogus

We utilized the RegExp.test strategy to check assuming the string contains numbers.

The forward slashes / / mark the beginning and end of the regular expression.

The \d character matches any digit from 0 to 9.

In the event that you at any point need assistance perusing a normal articulation, look at this regex cheatsheet from MDN.

The test() strategy returns valid on the off chance that the standard articulation is matched in the string, generally bogus is returned.

Alternatively, you can use the [0-9] range. This may be more readable if you're not familiar with the special characters in regular expressions.

The accompanying model likewise checks in the event that a string contains no less than one number.


index.js

const str1 = 'hi 42 world';
const str2 = 'hi world';

function containsNumber(str) {
  return/[0-9]/.test(str);
}

console.log(containsNumber(str1));//👉️ valid
console.log(containsNumber(str2));//👉️ bogus

Instead of using the \d special character, we used the [0-9] character class.

This character class is utilized to determine a scope of numbers that we need to match.

The [0-9] territory ought to be a smidgen more discernible than the \d character in the event that you're curious about normal articulations.

Further Perusing

  • Check assuming String contains just Letters and Spaces in JS

  • Check assuming that letter in String is Capitalized or Lowercase in JS


More Stories

Cover Image for Convert Array of Numbers to Array of Strings in JavaScript

Convert Array of Numbers to Array of Strings in Ja ...

Convert Array of Numbers to Array of Strings in JavaScript...

Matheus Mello
Matheus Mello
Cover Image for Check if specific Text exists on the Page using JavaScript

Check if specific Text exists on the Page using Ja ...

Check if specific Text exists on the Page using JavaScript...

Matheus Mello
Matheus Mello
Cover Image for Check if First Letter of String is Uppercase in JavaScript

Check if First Letter of String is Uppercase in Ja ...

Check if First Letter of String is Uppercase in JavaScript...

Matheus Mello
Matheus Mello