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


您可以使用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方法,可以使其不敏感


例如,您可以使用indexOf:

if (url.indexOf(substring)>=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,并执行以下步骤:

  • 设O为CheckObjectCoercible(this value) 。
  • 设S是ToString(O) 。
  • ReturnIfAbrupt(S) 。
  • 让searchStr为ToString(searchString) 。
  • ReturnIfAbrupt(searchStr) 。
  • 让pos为ToInteger(position) 。 (如果position undefined ,则此步骤产生值0 )。
  • ReturnIfAbrupt(pos) 。
  • 让len是S中元素的数量。
  • 让我们start min(max(pos, 0), len) 。
  • 让searchLen成为searchLen中的字符searchStr 。
  • 如果存在任何不小于start的整数k ,使得k + searchLen不大于len ,并且对于小于searchLen所有非负整数j ,则S位置k+j处的字符与位置j处的字符相同searchStr ,返回true ; 但是如果没有这样的整数k ,则返回false 。
  • 链接地址: http://www.djcxy.com/p/2055.html

    上一篇: javascript if statement if url contains substring

    下一篇: Check a string that MUST contain another string