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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With