JavaScript Check if String Contains at Least One Number

Reading Time: 3 minutes
996 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.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.