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.
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
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))
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM