/

A Regular Expression to Capture a URL Without Query String Parameters

A Regular Expression to Capture a URL Without Query String Parameters

When dealing with URLs, there may be cases where you need to extract the base URL without any query string parameters. Whether it’s an “http” or “https” link, here’s a regular expression that can help you achieve that:

1
/^(http[^?#]+).*/gm

Let’s take a look at an example to understand how it works:

1
2
3
const regex = /^(http[^?#]+).*/gm;
const result = regex.exec("https://test.com?test=2");
console.log(result);

The code snippet above will output the following result:

1
2
3
4
5
6
7
[
'https://test.com?test=2',
'https://test.com',
index: 0,
input: 'https://test.com?test=2',
groups: undefined
]

As you can see, the regular expression correctly captures the base URL without the query string parameter (“?test=2”).

Example Result

This regular expression captures the base URL by matching “http” or “https,” followed by any character that is not a “?” or “#” sign. The “.*” at the end allows for any additional characters in the URL.

Using this regular expression, you can extract the base URL from URLs with or without query string parameters, providing a versatile solution for your URL parsing needs.

Tags: regular expression, URL parsing, query string parameters, JavaScript