How to use # as part of CoffeeScript heregex?

后端 未结 2 616
萌比男神i
萌比男神i 2021-01-19 10:42

I\'m trying to match the hash fragment of a jQuery Mobile URL like this:

    matches = window.location.hash.match ///
        #                   # we\'re in         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-19 11:00

    Escape it in the usual fashion:

    matches = window.location.hash.match ///
        \#                  # we're interested in the hash fragment
        (?:.*/)?            # the path; the full page path might be /dir/dir/map.html, /map.html or map.html
                            # note the path is not captured
        (\w+\.html)$        # the name at the end of the string
        ///
    

    That will compile to this regex:

    /\#(?:.*\/)?(\w+\.html)$/
    

    And \# is the same as # in a JavaScript regex.

    You could also use the Unicode escape \u0023:

    matches = window.location.hash.match ///
        \u0023              # we're interested in the hash fragment
        (?:.*/)?            # the path; the full page path might be /dir/dir/map.html, /map.html or map.html
                            # note the path is not captured
        (\w+\.html)$        # the name at the end of the string
        ///
    

    But not many people are going to recognize \u0023 as a hash symbol so \# is probably a better choice.

提交回复
热议问题