如何使用#作为CoffeeScript heregex的一部分?

编程入门 行业动态 更新时间:2024-10-28 12:29:31
本文介绍了如何使用#作为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的一部分?

本文发布于:2023-06-03 08:56:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/470180.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   CoffeeScript   heregex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!