简体   繁体   中英

Regex to retrieve numbers from string

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!

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

var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

This will print 1234561613213213

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM