下面是一个非常简单的正则表达式代码,它在 php 和 ruby 中可以正常工作,但在 JS 中不能正常工作。请帮助我让它工作:
var r = /:[a-z]+/
var s = '/a/:b/c/:d'
var m = r.exec(s)
// now m is [":b"]
// it should be [":b", ":d"]
// because that's what i get in ruby and php
最佳答案
使用正则表达式 exec()
with g
(全局)修饰符用于在循环中获取所有匹配项。
var str = '/a/:b/c/:d'
var re = /:[a-z]+/g
var matches;
while (matches = re.exec(str)) {
// In array form, match is now your next match..
}
您也可以使用字符串。 match()
方法在这里。
var s = '/a/:b/c/:d',
m = s.match(/:[a-z]+/g);
console.log(m); //=> [ ':b', ':d' ]
关于javascript - 简单的正则表达式/:[a-z]+/not working as expected in javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23970224/