how to get part of url in javascript

There are several ways to get parts of a URL in JavaScript. Here are a few examples:

  1. Using substring() method:
index.tsx
var url = "https://www.example.com/path1/path2/page.html";
var domain = url.substring(url.indexOf("//")+2, url.lastIndexOf("/"));
console.log(domain); // "www.example.com/path1/path2"
184 chars
4 lines
  1. Using split() method:
index.tsx
var url = "https://www.example.com/path1/path2/page.html";
var domain = url.split("/").slice(0,3).join("/");
console.log(domain); // "https://www.example.com"
159 chars
4 lines
  1. Using regex:
index.tsx
var url = "https://www.example.com/path1/path2/page.html";
var domain = url.match(/^https?\:\/\/[^\/?#]+/)[0];
console.log(domain); // "https://www.example.com"
161 chars
4 lines

In the above code snippets, url variable is the URL string and domain variable is the part of the URL that we want to extract.

The first method uses the substring() method to extract the domain part of the URL. We first find the starting index of the domain using indexOf() method and ending index using lastIndexOf() method, and then extract the substring between those indexes

The second method uses the split() method to split the URL into an array of substrings using the forward slash as a separator. We then slice the first three elements of the array and join them back together using forward slash as a separator.

The third method uses a regex pattern to match the domain part of the URL. Here, we are using ^ character to specify the starting of the string and [^\/?#]+ to match one or more characters that are not /, ? or #.

gistlibby LogSnag