本文将教您检查 URL 是否包含字符串。我们将使用String.prototype.incluesOf()、
正则表达式和String.prototype.includes()
目录
3.用于toString( ).includes()检查URL是否包含字符串
1.用于indexof()检查URL是否包含字符串
indexOf
当 URL 包含字符串时,您可以使用from 方法检查字符串是否存在String.prototype.indexOf()
。因此,参数 of indexOf
应该是您的搜索字符串。
该indexOf
方法通过在 URL 中搜索该字符串的第一次出现来工作。同时,您需要使用indexOf
on,window.location.href
因为它包含当前网页的 URL。
在下面的代码中,我们使用indexOf
onwindow.location.href
检查 URL 是否包含 string 'tutorial'
if (window.location.href.indexOf("tutorial") > -1) { alert("The web page contains the string 'tutorial'"); }
结果:
2.使用正则表达式检查URL是否包含字符串
您可以使用正则表达式模式来搜索 URL 是否包含字符串。同时,您将需要test()
来自 的方法RegExp.prototype.test()
。
由于您要在 URL 中查找字符串,因此要搜索的模式应该是字符串本身。在下面的代码中,我们使用该test()
方法来匹配'html'
DelftStack 网站上的字符串。
代码:
if (/html/.test(window.location.href)) { alert("The web page contains the string 'html'"); }
结果:
3.用于toString( ).includes()检查URL是否包含字符串
toString()
和方法的组合includes()
可以确定 URL 是否包含字符串。返回对象的toString()
字符串版本。
所以,我们需要它,因为我们将从 中获取 URL window.location
,它是一个对象。由于我们已经有了 的字符串版本window.location
,我们可以使用该includes()
方法来确定它是否包含字符串。
但是,该includes()
方法执行区分大小写的搜索,并且搜索hello
不会匹配Hello
。在下一个代码块中,我们使用了includes
方法并toString
确定 URL 是否包含字符串"google"
。
代码:
if (window.location.toString().includes("google")) { alert("There is 'google' in the URL"); }
输出: