JavaScript Check if String Contains at Least One Number

Share this Article
Reading Time: 3 minutes
423 Views

Inside this article we will see the concept i.e JavaScript check if String contains at least one Number. Article contains the classified information about checking at least a digit inside string by using javascript regular expressions and/or methods. Tutorial is super easy to understand and implement it in your code as well.

If you are looking for a solution to check a digit inside a string in javascript using regular expression then this article will help you a lot for this.

Learn More –

Let’s get started.

Example #1 – Check a Digit in a String Using [0-9]

Here,

We will use javascript regular expression [0-9] a pattern to check a digit exists or not inside a string.

//...

<script>

var str1 = 'Welcome 123 to Online Web Tutor';
var str2 = 'Sanjay Kumar';

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

console.log(containsNumber(str1)); // true
console.log(containsNumber(str2)); // false
  
</script>

//...

Executing inside browser console window

Example #2 – Check a Digit in a String Using \d

Here,

We will use javascript regular expression \d a pattern to check a digit exists or not inside a string.

//...

<script>

var str1 = 'Welcome 123 to Online Web Tutor';
var str2 = 'Sanjay Kumar';

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

console.log(containsNumber(str1)); // true
console.log(containsNumber(str2)); // false
  
</script>

//...

Executing inside browser console window

We hope this article helped you to learn JavaScript Check if String Contains at Least One Number in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5