RegExp giving `null` for matches – works in regex101.com

I have a simple regex for matching parts of the current navigator url.

It is supposed to be finding some specific parts of the url which will be in the format:

https://localhost:9443/client/#chart/680

or

https://localhost:9443/client/#chart/680/123

This is working fine when I test it on RegEx101

https://regex101.com/r/ByBgMO/1

However when implimented it returns null for the matches, why?

Here is the code in question:

// pull out the sections [https://...../ | #chart/123 | [/123]]
const urlRegEx = new RegExp("^(.+\/)(#chart\/\d+)(\/\d+)?", "ig");

const url = document.location.href.split("^")[0];
// url = https://localhost:9443/client/#chart/680

const matches = urlRegEx.exec(url);
// matches = null

console.log("Chart.loadChartConfig().urlMatches: ", { url: url, matches: matches });

For info: the document.location.href.split("^")[0] is because the url might have sections used for display only that are preceeded by a ^ – I don’t care about these.

>Solution :

\ has special meaning in JavaScript strings, so you need to escape those that you mean literally:

const urlRegEx = new RegExp("^(.+\\/)(#chart\\/\\d+)(\\/\\d+)?", "ig");

const url = 'https://localhost:9443/client/#chart/680';

const matches = urlRegEx.exec(url);

console.log("Chart.loadChartConfig().urlMatches: ", { url: url, matches: matches });

Leave a Reply