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!
user1937021user1937021
asked Sep 3, 2015 at 8:02
2 Answers 2
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]);
Sign up to request clarification or add additional context in comments.
1 Comment
Wiktor Stribiżew
If OP does not need to return multiple matches with captured groups, why use
exec
? I think match
is enough here (without g
modifier).var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);
This will print 1234561613213213
2 Comments
user1937021
Hi, thanks, but how can I save them both in two different variables?
I-Kod
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.
lang-js
var numbers = string.match(/\d+/g);
Check Demo