我怎么能这样做呢:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
我怎么能这样做呢:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
当前回答
试试这个:
<script type="text/javascript">
$(document).ready
(
function ()
{
var regExp = /franky/g;
var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
if(regExp.test(testString)) // This doesn't work, any suggestions.
{
alert("your url contains the name franky");
}
}
);
</script>
其他回答
你可以像这样使用indexOf:
if(window.location.href.indexOf("franky") != -1){....}
还要注意字符串的href,否则你会这样做:
if(window.location.toString().indexOf("franky") != -1){....}
您需要添加href属性并检查indexOf而不是contains
< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <脚本type = " text / javascript”> $(文档)时函数(){ if (window.location. ref. indexof ("franky") > -1) { 提示("您的url包含名称franky"); } }); > < /脚本
窗口。location不是String,但它有toString()方法。所以你可以这样做:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
从旧的Mozilla文档:
位置对象有一个toString 方法返回当前URL。你 也可以将字符串赋值给 window.location。这意味着你 可与窗口工作。位置就好像它 在大多数情况下都是字符串。 有时候,比如当你需要的时候 调用一个String方法,你 必须显式调用toString。
这是我的代码♥
function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
return true;
}
else {
console.log("Error", "The link is not valid");
}
return false;}
if (window.location.href.indexOf("franky") != -1)
会这么做的。或者,你可以使用regexp:
if (/franky/.test(window.location.href))