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

JS regex replace URL parts

Given this relative URL: /member-directory/john-doe/bp-memberships/?action=cancel&sub=12 where /john-doe/ changes. I’m trying to change this part /john-doe/bp-memberships/ to something else.

I’ve tried this:

const regex = '(?:([^/]+)/){2}';
console.log(p.replace(regex, 'testttt'));

But it doesn’t work at all. On regex testers, this matches exactly what I want. What am I doing wrong here?

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

>Solution :

Regexes aren’t strings.

Use this site regex101 and select the ECMAScript flavour on the left side bar.

Your regex isn’t valid in javascript, you need to escape the / chars and add a starting and closing / ‘character’.

Working code:

const regex = /(?:([^\/]+)\/){2}/;
console.log(p.replace(regex, 'testttt'));
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