Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the largest number from a string using a regular expression

I have a variable string like:

var myString = "857nano620348splitted3412674relation5305743"; 

How do I find the largest number from this?

I have tried like the below without any success.

var matches = myString.match(/d+/g); 
like image 671
CodeDecode Avatar asked Mar 06 '14 17:03

CodeDecode


People also ask

How do you find the largest number in a string?

Consider the following String: String test= "0, 1, 3, 2, 2, 1, 1, 4, 2, 5, 1, 1, 0, 1, 241"; The largest value is the last value, 241 .

What is [] in regular expression?

The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a [] . It provides a range construct. The regex [a-z] will match any letter a through z.


1 Answers

I'd go for

var myString = "857nano620348splitted3412674relation5305743"; var largest  = Math.max.apply(null, myString.match(/\d+/g)); 

FIDDLE

myString.match(/\d+/g) returns an array of the numbers, and using Math.max.apply(scope, array) returns the largest number in that array.

like image 109
adeneo Avatar answered Sep 24 '22 03:09

adeneo