为什么如果我将 /g
添加到 lineRoute
parseRoute
函数只返回一次?
pkt = "Record-Route: <sip:10.1.20.40;lr;r2=on>\r\nRecord-Route: <sip:10.1.20.40:80;transport=ws;r2=on;lr=on>\r\n"
parseRoute = (pkt) ->
lineRoute = /Route\:/
route = ""
for line in pkt.split '\r\n'
if lineRoute.test line
tmp = line.split ': '
route += tmp[1] + ", \r\n"
return route
最佳答案
当您重用 RegEx 对象时,对 test
的每次调用都将从上一个匹配项的索引开始。所以在每次调用测试之间你必须重置这个索引:
lineRoute.lastIndex = 0
你的功能:
parseRoute = (pkt) ->
lineRoute = /Route\:/
route = ""
for line in abc
lineRoute.lastIndex = 0;
if lineRoute.test line
tmp = line.split ': '
route += tmp[1] + ", \r\n"
return route
此属性仅在全局标志设置为 /g
时使用。这解释了为什么当您不使用全局标志时它会起作用。
在这里阅读更多信息 https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions (搜索 lastIndex
)
关于javascript - 带或不带/g 的正则表达式 (CoffeeScript/JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12140303/