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?
>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'));