Split a URL in JavaScript after every forward slash?

JavascriptWeb DevelopmentObject Oriented Programming

To split a URL, use the split() method. Use toString() before that. Let us see an example

Example

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

Above, we have set forward slash in the split() function, since we need to split the URL after every such slash.

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo150.js. This will produce the following output −

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',
   ''
]
raja
Published on 11-Sep-2020 08:33:50
Advertisements