没有GET参数,url上的正则表达式无法拆分哈希值

时间:2015-09-08 21:25:32

标签: javascript regex

我几乎设法实现了我的目标:检查有效网址的函数然后返回其部分。一个有效的url可能是无模式或无协议的(这用于前端监听textarea和后端解析结果来自刮取的url及其标记)。

以下是工作示例: http://jsfiddle.net/6v1u5w1f/2/

var url = {
check:function( url ){
	var urlPattern = /((http|ftp|https):)?\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
	var patt = new RegExp( urlPattern );
	return patt.exec( url );
},
getParts: function( url ){
	url = this.check( url );
    if( !url ) return false;
 			var singleUrlPattern =/^(?:(.*?):)?(\/\/)?(?:[^\/\.]+\.)*?([^\/\.]+)\.?([^\/]*)(?:([^?]*)?(?:\?([^#]*))?)?(.*)?/;
   			return singleUrlPattern.exec( url[0] );
   	}
};


var urls = {
 schema_less:	'//cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
 http: 			'http://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
 https: 		'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
 get: 			'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg?this=that',
 hash: 			'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg#this=that',
 getAndHash:		'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg?this=that#dogs=cats',
 none: 			'cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
 sentence:		'bob https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg dog',
 barUrl:			'hi there this is my url: mazonaws.com/img/636/nl_nbp.jpg' };

//loop each url and run through the getParts function and print what it returns
for( var keya in urls ){
  console.log( keya+':' );
  console.log( url.getParts( urls[keya] ) );
  console.log( '               ' );    
}

在示例中,它将循环遍历一系列poss url模式,并控制台记录函数的结果。

问题是只在url中使用hash,我无法将其从url的路径中拆分出来。当有一个GET参数时,它会找到但不只是一个哈希..

1 个答案:

答案 0 :(得分:0)

考虑到您已尝试过的内容以及问题的范围,您可以使用以下表达式来匹配网址:

(?:(https?|ftp):\/\/)?\/*([^:\/\s]+)((\/\w+)*\/)([-.\w]+[^#?\s]*)?(?:\?([^#\s]*))?(#[-\w@?^=%&;\/~+#]+)?

Test online and read the explanation pane on the right

免责声明:此正则表达式确实存在一些误报,与“/”匹配任何内容,因为URI与文本中的任何单词都没有完全不同。此外,它不包括所有有效的URI。它只是作为OP所述内容的方法。

然而,如果您尝试解析网址,则正则表达式不适用于此。浏览器已经这样做了。请检查以下代码:

var urls = {
  schema_less:	'//cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
  http: 		'http://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
  https: 		'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
  get: 			'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg?this=that',
  hash: 		'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg#this=that',
  getAndHash:	'https://cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg?this=that#dogs=cats',
  none: 		'cartassets.s3.amazonaws.com/img/636/nl_nbp.jpg',
};

var parseURL = document.createElement('a');

for( var keya in urls ){
  parseURL.href = urls[keya];
  ['href','protocol','host','hostname','port','pathname','search','hash'].forEach( function(part) {
    document.write("<br />", keya , ": ", part, ": ", parseURL[part]);
  });
}