为什么我将/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
答案 0 :(得分:1)
当您重用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
)