我怎么能这样做呢:
<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>
当前回答
我喜欢创建一个布尔值,然后在逻辑if中使用它。
//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);
if (!onLoginPage) {
console.log('redirected to login page');
window.location = "/login";
} else {
console.log('already on the login page');
}
其他回答
窗口位置是一个包含多个方法和道具的对象,其中一些是与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
位置对象
试试这个:
<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>
使用Window.location.href获取javascript格式的url。这是一个 属性,该属性将告诉您浏览器的当前URL位置。 将属性设置为其他内容将重定向页面。
if (window.location.href.indexOf('franky') > -1) {
alert("your url contains the name franky");
}
我喜欢创建一个布尔值,然后在逻辑if中使用它。
//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);
if (!onLoginPage) {
console.log('redirected to login page');
window.location = "/login";
} else {
console.log('already on the login page');
}
if (window.location.href.indexOf("franky") != -1)
会这么做的。或者,你可以使用regexp:
if (/franky/.test(window.location.href))