所以基本上我想为网站做一些不同的事情,如果网址包含特定的字符串,请说:'foo'
所以这就是我所拥有的:
var url = document.URL;
var substring = 'foo';
if(the substring is in the url){
//do something
}
else{
//do something
};
那么if()
可以实现这一目标吗?
答案 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,并执行以下步骤:
- 让
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
中的字符数。- 如果存在任何小于{1}的整数
醇>k
,k + searchLen
不大于len
,并且所有非负整数j
小于searchLen
}k+j
的{{1}}位置的字符与S
的{{1}}位置的字符相同,返回j
;但如果没有这样的整数searchStr
,请返回true
。