Categories
JavaScript Answers

How to find the largest number from a string using a regular expression with JavaScript?

Spread the love

Sometimes, we want to find the largest number from a string using a regular expression with JavaScript.

In this article, we’ll look at how to find the largest number from a string using a regular expression with JavaScript.

How to find the largest number from a string using a regular expression with JavaScript?

To find the largest number from a string using a regular expression with JavaScript, we can use the JavaScript string’s match method with the Math.max method.

For instance, we write:

const myString = "857nano620348splitted3412674relation5305743";
const largest = Math.max(...myString.match(/\d+/g));
console.log(largest)

We call myString.match with a regex to return all the numbers.

Then we call Math.max with all the returned number strings by using the spread operator to spread them as arguments.

As a result, largest is 5305743.

Conclusion

To find the largest number from a string using a regular expression with JavaScript, we can use the JavaScript string’s match method with the Math.max method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *