javascript if statement if url contains substring
This question already has an answer here:
You can use the indexOf method
// 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;
}
Here's some sample usage:
var url = document.URL;
var substring = 'foo';
if (contains(url.toLowerCase(), substring.toLowerCase()) {
// Contains string
}
The contains function is case sentitive , however; as demonstrated in my example, you can make it incasesensitive by calling the StringPrototype.toLowerCase Method
例如,您可以使用indexOf:
if (url.indexOf(substring)>=0) {
This is a forward-looking answer, and won't work in current implementations.
ECMAScript 6 is currently defining a String.prototype.contains
method. This will allow you to do:
if (url.contains(substring)) {
Again, this is a future addition. Currently ECMAScript 6 (Harmony) is being drafted, and this could technically be removed, though it doesn't seem likely.
Current draft:
15.5.4.24 String.prototype.contains (searchString, position = 0 )
The contains method takes two arguments, searchString and position, and performs the following steps:
O
be CheckObjectCoercible(this value)
. S
be ToString(O)
. ReturnIfAbrupt(S)
. searchStr
be ToString(searchString)
. ReturnIfAbrupt(searchStr)
. pos
be ToInteger(position)
. (If position
is undefined
, this step produces the value 0
). ReturnIfAbrupt(pos)
. len
be the number of elements in S
. start
be min(max(pos, 0), len)
. searchLen
be the number of characters in searchStr
. k
not smaller than start such that k + searchLen
is not greater than len
, and for all nonnegative integers j
less than searchLen
, the character at position k+j
of S
is the same as the character at position j
of searchStr
, return true
; but if there is no such integer k
, return false
. 上一篇: 布尔和布尔在C#之间的区别?