0

I have this string:

var string = "look1_slide2";

I would like to extract the the look number ie 1 and the slide ie 2 and save them in two different variables, I guess I could do it with a Regex but not sure how. Any help? The string will always have that format btw

Thanks!

asked Sep 3, 2015 at 8:02
6
  • What have you tried? it's very simple var numbers = string.match(/\d+/g); Check Demo Commented Sep 3, 2015 at 8:03
  • possible duplicate of how to find a number in a string using javascript Commented Sep 3, 2015 at 8:06
  • I guess the main problem here is not the regex but variable assignment, right? Commented Sep 3, 2015 at 8:20
  • well yes, but I think I still need to use a hash so the page is bookmarkable. Commented Sep 3, 2015 at 8:23
  • Check this demo. Commented Sep 3, 2015 at 8:26

2 Answers 2

1

Since your string is always in that format you can simply read second and third entries of the returned regex matches array :

var string = 'look1_slide2';
var regex = /look(\d)_slide(\d)/g;
matches = regex.exec(string);
console.log(matches[1]);
console.log(matches[2]);

See RegExp.exec() doc

answered Sep 3, 2015 at 8:29
Sign up to request clarification or add additional context in comments.

1 Comment

If OP does not need to return multiple matches with captured groups, why use exec? I think match is enough here (without g modifier).
0
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

This will print 1234561613213213

answered Sep 3, 2015 at 8:08

2 Comments

Hi, thanks, but how can I save them both in two different variables?
The thing is how your number is represented? if your string pattern is look1_look2 then you can easily know that after '1' there is special character means no other number. You can differentiate numbers with this logic. 1 followed by '_' means 1 is alone and 2 followed by null character means 2 is alone save it with different variables. i.e Check the end of each number if next character is not number save into variable.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.