所以基本上,如果 url 包含特定的字符串,我想为网站做一些不同的事情,让我们说:'foo'
所以这就是我所拥有的:
var url = document.URL;
var substring = 'foo';
if(the substring is in the url){
//do something
}
else{
//do something
};
那么,如何if()才能使这成为可能呢?
所以基本上,如果 url 包含特定的字符串,我想为网站做一些不同的事情,让我们说:'foo'
所以这就是我所拥有的:
var url = document.URL;
var substring = 'foo';
if(the substring is in the url){
//do something
}
else{
//do something
};
那么,如何if()才能使这成为可能呢?
您可以使用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
}
但是, contains 函数是区分大小写的;如我的示例所示,您可以通过调用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为 中的字符数searchStr。- 如果存在任何
k不小于 startk + searchLen且不大于len的整数,并且对于所有j小于的非负整数searchLen,在位置的字符与在位置的k+j字符S相同,返回;但如果没有这样的整数,则返回。jsearchStrtruekfalse