【问题标题】:How to check if the URL contains a given string?如何检查 URL 是否包含给定的字符串?
【发布时间】:2011-06-03 13:56:03
【问题描述】:

我怎么能做这样的事情:

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

【问题讨论】:

  • "window.location.contains is not a function"

标签: javascript jquery url


【解决方案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;}

【讨论】:

    【解决方案2】:

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

    The Location Object

    【讨论】:

      【解决方案3】:

      相反,我喜欢这种方法。

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

      它适用于许多情况。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          您需要添加 href 属性并检查 indexOf 而不是 contains

          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <script type="text/javascript">
            $(document).ready(function() {
              if (window.location.href.indexOf("franky") > -1) {
                alert("your url contains the name franky");
              }
            });
          </script>

          【讨论】:

          • 我有一个像这样的长 URL,preview.tbwabox.co.nz/_v005/index.html#buying-a-car,我想检查字符串是否有“buying-a-car but the script”不起作用?
          • @Vennsoh 您找不到“买车”,因为您需要查看window.location.hash 而不是window.location.href。只需在 OP 的函数中交换这些值。
          • @J.W.为什么`>-1`我们不能使用`>0`?
          • @Elshan 因为严格来说,.href.indexOf("franky") can return a value of 0 如果.href 以“franky”开头。当然,在这种情况下,它永远不会像.href 总是以协议开头,通常是“http:”或“file:”。尽管如此,在与indexOf() 的结果进行比较时,您应该始终使用 >-1、>=0 或我的偏好!==-1。
          • 我有一个值数组,想看看 Url 是否有任何值,并给我匹配条件的数组索引。我怎么做?谢谢。
          【解决方案6】:

          正则表达式对于很多人来说会更理想,因为有字边界\b 或类似设备。当0-9a-zA-Z_ 中的任何一个位于下一个匹配项的那一侧,或者当字母数字字符连接到行或字符串的结尾或开头时,就会出现单词边界.

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

          如果您使用if(window.location.href.indexOf("sam"),您将获得flotsamsame 的匹配项,等等。 tom 将匹配番茄和明天,没有正则表达式。

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

          此外,添加其他过滤器就像

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

          我们来谈谈(?:\b|_)。 RegEx 通常将_ 定义为word character,因此它不会导致单词边界。我们使用这个(?:\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}](filters|in|any|alphabet)[^\p{L}]

          【讨论】:

          • 正则表达式的唯一缺点是它们是“只写”(即无法读取);)
          • @RayLoveless 是的,在没有(?#comments) 和freespacing # comments 的语言中,比如javascript。然而,这本书并不难读。 // 当我在 javascript 中使用复杂的正则表达式时,我会保留一个可以编辑的注释副本,哈哈。
          【解决方案7】:

          假设你有这个脚本

          <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&amp;over=flow

          写入&lt;p id="response"&gt; 的文本将是stack

          【讨论】:

            【解决方案8】:

            放入你的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');
                            }
            

            【讨论】:

            • 我不知道~,所以我查了一下:"~ 是把indexOf() 找到的返回值变成真值的技巧(同时使不-发现是假的)。人们使用它是因为它截断数字的副作用......“ - stackoverflow.com/a/12299678/3917091
            【解决方案9】:

            window.location 不是字符串,但它有一个toString() 方法。所以你可以这样做:

            (''+window.location).includes("franky")
            

            window.location.toString().includes("franky")
            

            来自old Mozilla docs

            Location 对象有一个 toString 返回当前 URL 的方法。你 也可以将字符串分配给 窗口位置。这意味着你 可以像使用 window.location 一样使用 在大多数情况下是一个字符串。 有时,例如当您需要时 要在其上调用 String 方法,您 必须显式调用 toString。

            【讨论】:

            • 在 Firefox 48 中,String.prototype.contains() 已被删除。仅使用 String.prototype.includes()。 See Here
            • @CaseyC 已更改。谢谢!
            【解决方案10】:

            正则表达式方式:

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

            或者在一个简单的语句中你可以使用:

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

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

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

            这会检查 href 是否包含192.168localhost AND 后跟:1337

            如您所见,当条件变得有点棘手时,使用正则表达式优于其他解决方案。

            【讨论】:

            • 不错。我用 if (window.parent.location.href.match(/\?/)) { window.parent.location = window.parent.location.pathname; } 并且效果很好......
            • 另外,如果我没有对比赛做任何事情,我觉得使用if(/franky/.test(location.href)) { /* regex matched */ } 会更简洁一些。
            • 是的,在这种情况下,test 绝对比match 干净。
            【解决方案11】:

            比较容易

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

            【讨论】:

              【解决方案12】:

              我喜欢创建一个boolean,然后在逻辑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');
              }
              

              【讨论】:

                【解决方案13】:

                像这样:

                    <script type="text/javascript">
                        $(document).ready(function () {
                            if(window.location.href.indexOf("cart") > -1) 
                            {
                                 alert("your url contains the name franky");
                            }
                        });
                    </script>
                

                【讨论】:

                • 调用window.location.indexOf和window.location.href.indexOf有什么区别?
                • @starsplusplus 没有任何区别。 window.location.hrefwindow.location developer.mozilla.org/en-US/docs/Web/API/Window.location 的别名
                • 上面的对我来说很好,但是对于两个变量如何检查它是否包含两个值
                • @VinothNarayan 您可以简单地在if 语句中添加另一个条件。要确保两者兼有,您可以使用 AND 运算符,即 Javascript 中的 &amp;&amp;if( window.location.href.indexOf("cart") &gt; -1 &amp;&amp; window.location.href.indexOf("box") &gt; -1 ) 要检查它是否具有其中一个值,请使用 OR 运算符,即两个竖线字符 || @ 987654329@
                【解决方案14】:
                if (window.location.href.indexOf("franky") != -1)
                

                会的。或者,您可以使用正则表达式:

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

                【讨论】:

                • 这两个选项之间的优缺点将是对这个答案的一个很好的补充。
                • 但如果我使用正则表达式,没人能读懂它;)
                【解决方案15】:

                使用 Window.location.href 获取 javascript 中的 url。它是 属性将告诉您浏览器的当前 URL 位置。 将属性设置为不同的值将重定向页面。

                if (window.location.href.indexOf('franky') > -1) {
                     alert("your url contains the name franky");
                }
                

                【讨论】:

                • 如何检查一个 url 是否是默认页面并且字符串 iam 检查不可见。例如 sample.com/homepage.aspx 是我的页面,我正在寻找字符串“主页”。 if((loc.toString().toUpperCase().indexOf('homepage') > -1)){} 工作正常,但是当我在 sample.com 上时(仍然指向 homepage.aspx),上面的代码将不起作用。如何也检查这种情况?请帮助!
                【解决方案16】:

                试试这个,它更短,和window.location.href一样工作:

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

                如果你想查看之前的网址:

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

                【讨论】:

                • @sixstarpro 我没有投反对票,但是,哦,我不知道,可能很明显,因为您给出的答案与 18 个月前发布的 this one 相同!此外,关于document.referrer 的额外信息与问题完全无关。
                【解决方案17】:

                document.URL 应该会给你URL

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

                【讨论】:

                  【解决方案18】:

                  试试 indexOf

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

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

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

                  【讨论】:

                    【解决方案19】:

                    试试这个:

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

                    【讨论】:

                      【解决方案20】:

                      你会像这样使用indexOf

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

                      还要注意为字符串添加href,否则你会这样做:

                      if(window.location.toString().indexOf("franky") != -1){....}
                      

                      【讨论】:

                        猜你喜欢
                        • 2018-06-14
                        • 1970-01-01
                        • 2012-03-28
                        • 2014-01-08
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-06-23
                        • 1970-01-01
                        • 2017-09-23
                        相关资源
                        最近更新 更多