Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading