Ad

Manipulate Urls With Regular Expressions Instead Of The Slip Approach

- 1 answer

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.

Ad

Answer

One way is to use replace to match last 3 with /, capture only the last / part in capture group and replace with the topics6 and value of captured group

enter image description here

let url = "http://www.my-site.com/topic1/topic2/topic3/topic4/topic5"

let func = (url) => {
  if ((url.match(/\//g) || []).length === 7) {
    const arr = url.replace(/(?:\/[^\/]+){2}(\/[^\/]+)$/, (m, g) => `\/topics6${g}`)
    return arr
  }
  return url
}

console.log(func(url))

Ad
source: stackoverflow.com
Ad