如何使用#作为CoffeeScript heregex的一部分? [英] How to use # as part of CoffeeScript heregex?
问题描述
我尝试匹配jQuery Mobile URL的散列片段,如下所示:
I'm trying to match the hash fragment of a jQuery Mobile URL like this:
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
///
但是,问题是#符号从编译的JS文件中的正则表达式中剪切,因为它被视为注释的开始。
However, the problem is that the # symbol gets chopped from the regex in the compiled JS file because it's treated as the start of a comment. I know I could switch to a normal regex, but is there any way to use # in a heregex?
推荐答案
转义到正确的正则表达式通常的方式:
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)$/
并且 \#
您也可以使用Unicode转义 \\\#
/ code>:
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.
这篇关于如何使用#作为CoffeeScript heregex的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!