Tags
Asked 2 years ago
16 Jun 2021
Views 148
Fatima

Fatima posted

How to find a number in a string using JavaScript?

How to find a number in a string using JavaScript?
Mahesh Radadiya

Mahesh Radadiya
answered Apr 27 '23 00:00

You can use regular expressions (regex) to find a number in a string using JavaScript.

Here is an example of how to use regex to find a number in a string:



var str = "The price is $10.99";
var num = str.match(/\d+/)[0];
console.log(num); // Output: 10

In this example, the match() method is used to find a number in the string str. The regular expression /d+/ matches one or more digits, and the [0] index is used to extract the first match. The resulting number is then logged to the console.

If you want to include decimal places in the number, you can modify the regular expression to include a decimal point and any following digits:



var str = "The price is $10.99";
var num = str.match(/\d+\.\d+/)[0];
console.log(num); // Output: 10.99

In this example, the regular expressio n /\d+\.\d+/ matches one or more digits followed by a decimal point followed by one or more digits. This matches the decimal number 10.99 in the string str.
Post Answer