Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Multiple Integers from a string in Javascript

I'm trying to set up my page so a user is able to type in a string like "25a89ss15s9 8 63" and it alerts the user "25, 89, 15, 9, 8, 63" and then further alerts the user "8, 9, 15, 25, 63, 89". So I'm trying to separate the integers from the string specified, and then sort them. Any ideas on how I would separate them into an Array or something close? I've tried a few examples from similar questions, but they seem to only work with one integer.

Any help would be appreciated, thanks.

like image 526
Josh Hayden Avatar asked Dec 04 '22 06:12

Josh Hayden


1 Answers

var string = "25a89ss15s9 8 63"; // Input
var list = string.match(/\d+/g); // Get a list of all integers
list.sort(function(x,y){         // Sort list
    return x - y;
});
// At this point, you have a sorted list of all integers in a string.

This code is using a RegEx (\d+ means: all consecutive digits = integers, /g means: select all occurrences). The String.match() method returns an array of all matched phrases, integers in this case.

Finally, the Array.sort method is invoked, passing a function as an argument, which sorts the array.

like image 199
Rob W Avatar answered Jan 22 '23 21:01

Rob W