简体   繁体   中英

Js regexp variable to get all matches in a string

There is the following code:

s.match(/\+[A-Za-z0-9_]+/);

I use it to get all Jade mixins from string. It works good for one Jade mixins in string ("+article"), but doesn't work for 2 mixins in string("+article +b") - it returns array with first item only. What did I do wrong? Thanks! Also it will be good to get array with values without plus!

Add global flag g in your regex

s.match(/\+[A-Za-z0-9_]+/g);

UPDATE : Demo with removed + symbol

 s = '+abc +4kk +ttt'; var res = s.match(/\\+[A-Za-z0-9_]+/g).map(function(v) { return v.substring(1) // get string after `+` }); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

Or regex with captured group

 var s = '+abc +4kk +ttt'; var reg = /\\+([A-Za-z0-9_]+)/g; var matches, res = []; while (matches = reg.exec(s)) { res.push(matches[1]); // get captured group value } document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

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