There are several ways to get parts of a URL in JavaScript. Here are a few examples:
index.tsx184 chars4 lines
index.tsx159 chars4 lines
index.tsx161 chars4 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