[英]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.我用它从字符串中获取所有 Jade mixin。 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.
它适用于字符串中的一个 Jade mixin ("+article"),但不适用于 string("+article +b") 中的 2 个 mixins - 它仅返回包含第一项的数组。 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在正则表达式中添加全局标志
g
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>');
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>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.