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
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.
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.
Yes, match
is the way to go:
var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[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]
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