How to use # as part of CoffeeScript heregex?

I am trying to map a hash fragment of a jQuery Mobile URL as follows:

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 /// 

However, the problem is that the # character is interrupted from the regular expression in the compiled JS file, as it was considered as the beginning of the comment. I know that I can switch to normal regex, but is there a way to use # in heregex?

+4
source share
2 answers

Escape as usual:

 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 /// 

This will be compiled for this regular expression:

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

And \# matches # in the JavaScript expression.

You can also use Unicode escape code \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 recognize \u0023 as a hash symbol, so \# is probably the best choice.

+5
source

Executor. Heregex comments are completely removed with a space using a simple regular expression ( /\s+(?:#.*)?/g ), so any non-white character before # (or its placement at the very beginning) works.

 $ coffee -bcs /// [#] /// /// (?:#) /// ///#/// // Generated by CoffeeScript 1.2.1-pre /[#]/; /(?:#)/; /#/; 
+3
source

Source: https://habr.com/ru/post/1398947/


All Articles