Manipulate urls with regular expressions instead of the slip approach Basically I have an url which looks like this structurally speaking:

http://www.my-site.com/topic1/topic2/topic3/topic4/topic5

and I want to do 2 things to it:

1. check the structure and validate it
2. replace both topic3 and topic4 with a new parameters called topic6


This is my solution for now but I am interested to build something more optimize.

if ((url.match(/\//g) || []).length === 7) {
    const arr = url.split('/');
    const topic5 = arr.pop();
    arr.pop();
    arr.pop();
    arr.push('topic6', topic5);
    return arr.join('/');
}


So as you can see, for the fact that I am not very good at regular expressions I have used another approach which doesn't look that good. I basically check for the number of / in the string, if tey are 7 it means that the structure of the url is good and that on this type of url I should apply the next steps. After that I grab the last param of the url and also remove it and next after that I remove the last 2 parameters and add the new one instead along with the topic5.

In case you you have a better approach, please let me know. I think that it can be done by writing less number of lines of code but as I said, I am not very familiar with regular expressions.
You seek to:


validate the url as coming from your site domain, then
replace the 3rd and 4th directories/topics with a single/new directory/topic.


This is a simple matter of preserving the substrings that you want to keep as "capture groups" and writing the new replace substring between the two capture groups.

In my demo, the new topic will be FOO.  I'm using negated character classes to match the directory names -- this is relatively "loose" validation.  If you require a tighter validation rule, see the 2nd snippet.  Click on Run code snippet below to see the resultant output.



const regex = /^((?:https?:\/\/)(?:w{3}\.)?my-site\.com\/(?:[^/]+\/){2})[^/]+\/[^/]+(\/[^/]+)$/;
      url = 'http://www.my-site.com/topic1/Topic2/topic3/topic4/слизень',
      replacement = '$1FOO$2';

document.write(url.replace(regex, replacement));




To tighten the validation beyond non-slashes as directory substrings AND extend the characters classes to include multibyte letters, you will need to manually expand the character classes to include the letters that you expect to qualify.  Please have a read of Regular expression with the cyrillic alphabet.



const regex = /^((?:https?:\/\/)(?:w{3}\.)?my-site\.com\/(?:[À-žа-яa-z\d-]+\/){2})[À-žа-яa-z\d-]+\/[À-žа-яa-z\d-]+(\/[À-žа-яa-z\d-]+)$/i;
      url = 'http://www.my-site.com/Schnecke/to-pic2/topic3/naaktslak/слизень',
      replacement = '$1FOO$2';

document.write(url.replace(regex, replacement));