Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers from a string using javascript

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

like image 490
FLuttenb Avatar asked Jul 25 '13 07:07

FLuttenb


People also ask

How do I convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the unary plus operator ( + ) The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.

What is number () in JavaScript?

Number encoding The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision.


2 Answers

Yes, match is the way to go:

var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
like image 136
georg Avatar answered Oct 20 '22 16:10

georg


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]
like image 32
Elias Van Ootegem Avatar answered Oct 20 '22 18:10

Elias Van Ootegem