简体   繁体   中英

Regular Expression with or without /g (CoffeeScript/JavaScript)

Why if I add /g to lineRoute parseRoute function just return only one occurrence?

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

When you reuse the RegEx object every call to test will start from index of the previous match. So in between each call to test you have to reset the this index:

lineRoute.lastIndex = 0

Your function:

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

This property is only used when the global flag is set /g . That explains why it works when you don't use the global flag.

Read more about it here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions (search for lastIndex )

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