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!

user1937021
  • 10,151
  • 22
  • 81
  • 143

2 Answers2

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

SiCK
  • 367
  • 4
  • 15
  • If OP does not need to return multiple matches with captured groups, why use `exec`? I think `match` is enough here (without `g` modifier). – Wiktor Stribiżew Sep 03 '15 at 08:31
0
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

This will print 1234561613213213

I-Kod
  • 199
  • 1
  • 11
  • Hi, thanks, but how can I save them both in two different variables? – user1937021 Sep 03 '15 at 08:10
  • 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. – I-Kod Sep 03 '15 at 08:20