如果url包含子字符串,则为javascript if语句

时间:2013-06-02 19:58:27

标签: javascript html url

所以基本上我想为网站做一些不同的事情,如果网址包含特定的字符串,请说:'foo'

所以这就是我所拥有的:

var url = document.URL;
var substring = 'foo';
if(the substring is in the url){
//do something
}
else{
//do something
};

那么if()可以实现这一目标吗?

3 个答案:

答案 0 :(得分:3)

您可以使用indexOf方法

// Function is used to determine whether a string contains another string
function contains(search, find) {
    ///<summary>Sees if a string contains another string</summary>
    ///<param type="string" name="search">The string to search in</param>
    ///<param type="string" name="find">The string to find</param>
    ///<returns type="bool">A boolean value indicating whether the search string contained the find string</returns>
    return search.indexOf(find) !== -1;
}

以下是一些示例用法:

var url = document.URL;
var substring = 'foo';
if (contains(url.toLowerCase(), substring.toLowerCase()) { 
// Contains string
}

包含功能大小写;但是;如我的示例中所示,您可以通过调用StringPrototype.toLowerCase方法

使其变得不敏感

答案 1 :(得分:1)

您可以使用indexOf例如:

if (url.indexOf(substring)>=0) {

答案 2 :(得分:0)

这是一个前瞻性的答案,并不适用于当前的实施。

ECMAScript 6目前正在定义String.prototype.contains方法。这将允许您:

if (url.contains(substring)) {

同样,这是未来的补充。目前正在起草ECMAScript 6(Harmony),这在技术上可以删除,但似乎不太可能。

目前的草案:

  

15.5.4.24 String.prototype.contains(searchString,position = 0)

     

contains方法接受两个参数searchString和position,并执行以下步骤:

     
      
  1. O成为CheckObjectCoercible(this value)
  2.   
  3. S成为ToString(O)
  4.   
  5. ReturnIfAbrupt(S)
  6.   
  7. searchStr成为ToString(searchString)
  8.   
  9. ReturnIfAbrupt(searchStr)
  10.   
  11. posToInteger(position)。 (如果positionundefined,则此步骤会生成值0)。
  12.   
  13. ReturnIfAbrupt(pos)
  14.   
  15. lenS
  16. 中的元素数量   
  17. start成为min(max(pos, 0), len)
  18.   
  19. searchLensearchStr中的字符数。
  20.   
  21. 如果存在任何小于{1}的整数kk + searchLen不大于len,并且所有非负整数j小于searchLen } k+j的{​​{1}}位置的字符与S的{​​{1}}位置的字符相同,返回j;但如果没有这样的整数searchStr,请返回true
  22.