我怎么能这样做呢:

<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>

你可以像这样使用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。


if (window.location.href.indexOf("franky") != -1)

会这么做的。或者,你可以使用regexp:

if (/franky/.test(window.location.href))

像这样:

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 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 (foo.indexOf("franky") >= 0)
{
  ...
}

您也可以尝试搜索(正则表达式)

if (foo.search("franky") >= 0)
{
  ...
}

文档。URL应该给你URL和

if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 

试试这个,它更短,工作完全像window.location.href:

if (document.URL.indexOf("franky") > -1) { ... }

如果你想检查之前的URL:

if (document.referrer.indexOf("franky") > -1) { ... }

regex方式:

var matches = !!location.href.match(/franky/); //a boolean value now

或者在一个简单的陈述句中你可以用:

if (location.href.match(/franky/)) {

我用这个测试网站是在本地运行还是在服务器上运行:

location.href.match(/(192.168|localhost).*:1337/)

它检查href是否包含192.168或localhost AND,后面跟着:1337。

如您所见,当条件变得有点棘手时,使用regex比其他解决方案更有优势。


使用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');
}

变得更容易

<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>

假设您有这个脚本

<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">的文本将被堆叠


放入你的js文件

                var url = window.location.href;
                console.log(url);
                console.log(~url.indexOf("#product-consulation"));
                if (~url.indexOf("#product-consulation")) {
                    console.log('YES');
                    // $('html, body').animate({
                    //     scrollTop: $('#header').offset().top - 80
                    // }, 1000);
                } else {
                    console.log('NOPE');
                }

正则表达式对于很多人来说是最优的,因为有单词边界\b或类似的设备。当0-9、a-z、a-z、_中的任何一个在下一次匹配的那一侧时,或者当字母数字字符连接到行或字符串的末尾或开头时,就会出现单词边界。

if (location.href.match(/(?:\b|_)franky(?:\b|_)))

如果你使用If (window.location.href.indexOf("sam"),你会得到flotsam和same的匹配。Tom将匹配番茄和明天,不需要正则表达式。

使它区分大小写就像删除i一样简单。

此外,添加其他过滤器非常简单

if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))

让我们来谈谈(?:\b|_)。RegEx通常将_定义为单词字符,因此它不会导致单词边界。我们使用this (?:\b|_)来处理这个问题。看看它是否在字符串的任何一侧找到\b或_。

其他语言可能需要使用类似

if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.

所有这些说起来容易

var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it 
// more for other filters like frank and billy

其他语言的正则表达式支持\p{L},但javascript不支持,这将使检测外来字符的任务变得容易得多。类似[^ \ p {L}](过滤器| | |字母表)[^ \ p {1})


如果将字符串转换为小写或大写,这将是一个很好的实践,因为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");
}

相反,我喜欢这种方法。

top.location.pathname.includes('franky')

它在很多情况下都有效。


窗口位置是一个包含多个方法和道具的对象,其中一些是与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

位置对象


这是我的代码♥

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('您不在问题页面'); }