How to Adjust Angular's URL matching pattern

2019-06-06 14:23发布

First things first, I want to adjust the pattern that Angular uses to match against for URL routing. I have found the function and it is running the URL location against these regex(s) found on line 5612 of angular.js (version http://code.angularjs.org/1.1.5/):

SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};

So why would I want to do that? I am using angular as the framework for a desktop AIR application. AIR applications can be built using HTML/JS, which is subsequently wrapped in AIR which provides access to the filesystem and OS. So this combination essentially allows you to build a multi-platform desktop web application with angular. Powerful stuff.

Here is the problem AIR has a custom address bar string which looks like app:/ rather than http://. So it has one slash instead of two. Angular uses the the address bar location to route the application, i.e. http://something.com/#/contactList means load the contactList view and its associated controller. My knowledge of regex is pretty (very) limited so I can't read the patterns I included above, but I am guessing that the one slash instead of two or something similar to that could be the problem.

My aim is to adjust the patterns so that app:/ would be a valid pattern and my hope is that the URI segment making and associated actions would still work.

2条回答
欢心
2楼-- · 2019-06-06 14:27

See Mozilla Regular Expressions doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

What @shaunhusain already explained in a comment is mostly correct, except for the following:

  • \w matches a single alphanumeric character or underscore
  • + matches 1 or more (not 0 or 1) of the previous character

Therefore, \w+ matches a word of length 1 or more characters.

You do need to modify the regex to only have one slash after the colon if you want to match something like app:/.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-06 14:41

Mark's answer is correct, here is what the altered Angular code looks like:

//** CHANGED REGEX TO MATCH ON 'app:/' as well
var SERVER_MATCH = /^([^:]+):\/+(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?      (\?([^#]*))?(#(.*))?$/, //var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,

I found it on line 5612 or thereabouts. Caveat: I have no idea if there will be deleterious side effects of making this change. The general idea was simply to get angular to match on app:/ as it would http:// so that it could function as an Air app.

查看更多
登录 后发表回答