如何在 JavaScript 中將 URL 按正斜槓進行分割?


要拆分一個 URL,使用 split() 方法。在此之前,使用 toString()。讓我們看一個例子

示例

var newURL="http://www.example.com/index.html/homePage/aboutus/";
console.log(newURL);
var splitURL=newURL.toString().split("/");
console.log(splitURL);

上面,我們在 split() 函式中設定了正斜槓,因為我們需要在每個這樣的斜槓後面拆分 URL。

要執行上述程式,您需要使用以下命令 −

node fileName.js.

輸出

這裡,我的檔名是 demo150.js。這將產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo150.js
http://www.example.com/index.html/homePage/aboutus/[
   'http:',
   '',
   'www.example.com',
   'index.html',
   'homePage',
   'aboutus',
   ''
]

更新日期:11-9-2020

8K+ 瀏覽

開始你的 職業生涯

透過完成課程來進行認證

開始
廣告