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
精彩评论