我怎么能这样做呢:
<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>
当前回答
窗口。location不是String,但它有toString()方法。所以你可以这样做:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
从旧的Mozilla文档:
位置对象有一个toString 方法返回当前URL。你 也可以将字符串赋值给 window.location。这意味着你 可与窗口工作。位置就好像它 在大多数情况下都是字符串。 有时候,比如当你需要的时候 调用一个String方法,你 必须显式调用toString。
其他回答
假设您有这个脚本
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
url表单是www.localhost.com/web_form_response.html?text_input=stack&over=flow
写入<p id="response">的文本将被堆叠
尝试indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
您也可以尝试搜索(正则表达式)
if (foo.search("franky") >= 0)
{
...
}
可以使用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('您不在问题页面'); }
变得更容易
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.href;
if(url.includes('franky')) //includes() method determines whether a string contains specified string.
{
alert("url contains franky");
}
});
</script>
如果将字符串转换为小写或大写,这将是一个很好的实践,因为indexof()方法是区分大小写的。
这将是如果你的搜索不区分大小写,你可以简单地使用indexOf()方法,而不将原始字符串转换为小写或大写:
var string= location.href;
var convertedString= string.toLowerCase();
if(convertedString.indexOf('franky') != -1)
{
alert("url has franky");
}
else
{
alert("url has no franky");
}