How to extract a Number from a String in JavaScript

Javascript extract number from string example; in this tutorial you will learn how to Extract a Number from a String in JavaScript. Here below we have beautifully explained how to extract number from a string in js;

Example 1:

In javascript we can use the str.replace method to extract a number from a string. For this we need to pass in a regular expression to replace all non-digit characters with an empty string.

The replace method returns a new string containing all the numbers from the original string.

const str = 'coding 1995 driver';

const replaced = str.replace(/\D/g, ''); // '1995'

let num;

if (replaced !== '') {
  num = Number(replaced); // 1995


Example 2:

This example uses match() function to extract number from string. An another method String.match to extract number from string in javascript.We pass a regular expression to the String.match method.

const str = 'coding 1995 driver';

const replaced = str.match(/\d+/); // ['1995']

let num;

if (replaced !== null) {
  num = Number(replaced[0]); // 1995