最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - URL Regex Improvement to allow localhost URL - Stack Overflow

programmeradmin2浏览0评论

I have a URL validator as below

(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)

which seems to cover most bases, but one that it can't, which is to allow localhost url's

I want to allow

http://localhost:8080

or

localhost:8080

But I don't want to allow simple string like

http://google

or

google

I have a URL validator as below

(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)

which seems to cover most bases, but one that it can't, which is to allow localhost url's

I want to allow

http://localhost:8080

or

localhost:8080

But I don't want to allow simple string like

http://google

or

google
Share Improve this question asked Jan 5, 2018 at 9:29 StevieBStevieB 6,55139 gold badges113 silver badges194 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can use this regex to allow localhost as a valid hostname:

(?:^|\s)((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)

RegEx Demo

Also you can use this RegEx

^((https?:\/\/)?(([\w-]+(?:\.[\w-]+)+)(:\d{1,5})?|([\w-]+:\d{1,5}))(\/\S*)?)$

RegEx Demo

发布评论

评论列表(0)

  1. 暂无评论