我怎么能这样做呢:
<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>
当前回答
您需要添加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"); } }); > < /脚本
其他回答
if (window.location.href.indexOf("franky") != -1)
会这么做的。或者,你可以使用regexp:
if (/franky/.test(window.location.href))
窗口位置是一个包含多个方法和道具的对象,其中一些是与URL相关的字符串,这样你就可以安全地搜索目标字符串:
const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// another option
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true
位置对象
你可以像这样使用indexOf:
if(window.location.href.indexOf("franky") != -1){....}
还要注意字符串的href,否则你会这样做:
if(window.location.toString().indexOf("franky") != -1){....}
这是我的代码♥
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;}
可以使用javascript字符串方法进行匹配
Const url = window.location.href; Const find = 'questions'; Const found = url.match(find); console.log (url); If (found !== null && found[0] === find){ console.log('你在问题页面'); }其他{ console.log('您不在问题页面'); }