我怎么能这样做呢:

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

当前回答

正则表达式对于很多人来说是最优的,因为有单词边界\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})

其他回答

假设您有这个脚本

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

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

尝试indexOf

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

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

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

像这样:

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

你可以像这样使用indexOf:

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

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

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