5

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

4 Answers 4

11

Yes, match is the way to go:

var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
Sign up to request clarification or add additional context in comments.

Comments

8

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]

1 Comment

thx for your answer. I figured it would be possible with split() too.
2

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+/));

Comments

-1

Try below code

var tz = "GMT-7";
var tzOff = tz.replace( /[^+-\d.]/g, '');
alert(parseInt(tzOff));

2 Comments

Please consider adding at least some words explaining why and how this code snippet does answer the OP question
This doesn't answer the OP's use case. It will only extract a single number for a start

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.