开发者

How to validate a url address and make sure it contains at least part of a url in javascript?

开发者 https://www.devze.com 2023-03-22 01:37 出处:网络
For this example lets say I want to validate a google plus profile URL in JavaScript. A typical google plus profile URL looks like:

For this example lets say I want to validate a google plus profile URL in JavaScript.

A typical google plus profile URL looks like:

https://plus.google.com/115025207826515678661

I basically want to make sure at least the beginning of what was typed in the text input form开发者_开发技巧 was:

http OR https ://plus.google.com/

How could this be done in JavaScript? Every example I find is just a simple validate if its a URL or not. Not if it contains part of a specific URL.


You could use a regex such as /^https?:\/\/plus\.google\.com/, but, I'd rather use the DOM.

This should do it...

var str = 'https://plus.google.com/115025207826515678661',
    a = document.createElement('a');

a.href = str;

var valid = ((a.protocol == 'http:' || a.protocol == 'https:')
              && a.hostname == 'plus.google.com'
            );

jsFiddle.


Do string comparision with indexOf("...") != -1

0

精彩评论

暂无评论...
验证码 换一张
取 消