最小化URL的正则义务



您可以帮助我使用以下所有条件,除了上一个条件以外的所有条件,而不是截面文章。P>

它应该匹配在家和部分页面(因为它们在URL的末尾(。

http://www.post.co.uk/
http://www.post.co.uk/news/
http://www.post.co.uk/news/celebrity-news/

而不是

http://www.post.co.uk/news/herjerher/jewkrjewrj

请注意,最后一个URL在URL的末尾没有BackSlash /

(http|https)://.*/[a-zA-Z'-]+/[a-zA-Z'-]+/?$
^(http|https)://www.post.co.uk/?$
^(http|https)://www.post.co.uk/[a-zA-Z'-]+/?
/^http://www.post.co.uk/([^/]+/){0,}$/

这意味着:

^: The word starts with
$: The word ends with
/: Stands for /
[^/]: All chars without /
[^/]+: At least one char which is not /
([^/]+/){0,}: The group of at least one char which is not / and a / is availabe for at least 0 times

使用URL构造函数

var fnIsValidURL = url => {
  try{ new URL( url ); } catch( e ) { return false; } 
  return true;
};
var hasSlashAtEnd = url => url.slice( -1 ) == "/";

现在将它们用作

var url = "http://www.post.co.uk/news/celebrity-news/";
if ( fnIsValidURL( url ) && hasSlashAtEnd( url ) )
{
   alert( "valid" );
}
else
{
   alert( "invalid" );
}

注意

  • 在使用此之前,请检查URL的浏览器兼容性。

尝试这个

/^http://www[.].*/$/

美元指定必须在结束之前必须的确切字符

最新更新