Extract numbers from a string using javascript

15,732

Solution 1

Yes, match is the way to go:

var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);

Solution 2

If the string is always going to look like this: "ch[num1]sl[num2]", you can easily get the numbers without a regex like so:

var numbers = str.substr(2).split('sl');
//chop off leading ch---/\   /\-- use sl to split the string into 2 parts.

In the case of "ch2sl4", numbers will look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or numbers.map(function(a){ return +(a);}.

If the string parts are variable, this does it all in one fell swoop:

var str = 'ch2fsl4';
var numbers = str.match(/[0-9]+/g).map(function(n)
{//just coerce to numbers
    return +(n);
});
console.log(numbers);//[2,4]

Solution 3

As an alternative just to show how things can be achieved in many different ways

var str = "ch2sl10";
var num1 = +(str.split("sl")[0].match(/\d+/));
var num2 = +(str.split("sl")[1].match(/\d+/));
Share:
15,732
FLuttenb
Author by

FLuttenb

Updated on June 04, 2022

Comments

  • FLuttenb
    FLuttenb almost 2 years

    I'd like to extract the numbers from the following string via javascript/jquery:

    "ch2sl4"
    

    problem is that the string could also look like this:

    "ch10sl4"
    

    or this

    "ch2sl10"
    

    I'd like to store the 2 numbers in 2 variables. Is there any way to use match so it extracts the numbers before and after "sl"? Would match even be the correct function to do the extraction?

    Thx