使用 JavaScript 檢查 URL 是否包含字串
本文將教你檢查 URL 是否包含字串。我們將使用 String.prototype.indexOf()、正規表示式和 String.prototype.includes() 進行檢查。
使用 indexOf() 檢查 URL 是否包含字串
當 URL 包含字串時,你可以使用 String.prototype.indexOf() 中的 indexOf 方法檢查字串是否存在。因此,indexOf 的引數應該是你的搜尋字串。
indexOf 方法通過在 URL 中搜尋該字串的第一次出現來工作。同時,你需要在 window.location.href 上使用 indexOf,因為它包含當前網頁的 URL。
在下面的程式碼中,我們在 window.location.href 上使用 indexOf 來檢查 URL 是否包含字串'tutorial'。
程式碼:
if (window.location.href.indexOf('tutorial') > -1) {
alert('The web page contains the string \'tutorial\'');
}
輸出:
.webp)
使用正規表示式檢查 URL 是否包含字串
你可以使用正規表示式模式來搜尋 URL 是否包含字串。同時,你需要 RegExp.prototype.test() 中的 test() 方法。
由於你要在 URL 中查詢字串,因此要搜尋的模式應該是字串本身。在下面的程式碼中,我們使用了 test() 方法來匹配 DelftStack 網站上的字串 'html'。
程式碼:
if (/html/.test(window.location.href)) {
alert('The web page contains the string \'html\'');
}
輸出:

使用 toString().includes() 檢查 URL 是否包含字串
toString() 和 includes() 方法的組合可以確定 URL 是否包含字串。toString() 返回物件的字串版本。
因此,我們將需要它,因為我們將從 window.location 獲取 URL,它是一個物件。由於我們已經有了 window.location 的字串版本,我們可以使用 includes() 方法來確定它是否包含字串。
但是,includes() 方法執行區分大小寫的搜尋,搜尋 hello 將不匹配 Hello。在下一個程式碼塊中,我們使用了 includes 方法和 toString 來確定 URL 是否包含字串 "google"。
程式碼:
if (window.location.toString().includes('google')) {
alert('There is \'google\' in the URL');
}
輸出:
.webp)
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn