我正在从Photoshop脚本升级到其他东西: 使用JavaScript我需要检查三个方面的网站地址的有效性。
在我的例子中,我正在查看www.somesite.com
到目前为止,这是代码:
URIArr = [
"https://www.somesite.com/find-work-home",
"www.somesite.com/",
"blahsomesite.com/bananas/stuff",
"something.somesite.com/bananas/cheese",
"blahsomesite.com/bananas/123",
"www.blah.somesite.m.com/bananas/5678",
"blah.somesite.comm/bananas/ook",
]
for (var i = 0; i < URIArr.length; i++)
{
var temp = URIArr[i];
var valid = checkURL(".somesite", temp);
if (!valid)
{
alert(temp + " is " + checkURL(".somesite", temp));
}
}
function removeTrailingSlashes(site)
{
return site.replace(/\/$/, "");
}
function checkURL(webstr, str)
{
// A dot (.) before and after "somesite"
// Nothing between ".somesite" and ".com/"
// Nothing between ".com" and the "/"
var test1 = false;
var test2 = false;
var test3 = false;
var c = ".com";
var haystack = str.toLowerCase();
var needle = webstr.toLowerCase();
haystack = removeTrailingSlashes(haystack);
if (!haystack.charAt(haystack .length) === "/")
haystack += "/";
var n = haystack.indexOf(needle);
var m = n + (needle.length);
// first check
if (str.charAt(n) && str.charAt(m) === ".") test1 = true;
//second check
var o = haystack.indexOf(c);
if (o-m === 0) test2 = true;
// third check
var p = o + (c.length);
var truncStr = haystack.substring(o, haystack.length);
var q = truncStr.indexOf("/") + o;
if (q-p === 0) test3 = true;
// final triplecheck
if ((test1 == true) && (test2 == true) && (test3== true)) return true
return false
}
问题是: - 我是否错过任何技巧(我注意到第三个条件我必须添加尾部斜线 - 即使它们可能不存在) 但更重要的 : - 这可以用(三)正则表达式重写吗?
这是Reginald X. Pression的工作吗?
答案 0 :(得分:0)
您可以将以下单个正则表达式用于所有三个测试:
\.somesite(?=\.com\/)
Js代码:
var regex = /\.somesite(?=\.com\/)/g;
var valid = regex.test(myString); //true if found.. else false
请参阅DEMO