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

Replace the string after second forward slash using a RegEx

Having a string (URL path) as for example: /this/is/some/url I would like to remove the first occurrence of / and change the string after the second forward slash (in the example some) by another string let’s say is. The result should be this/is/a/url and this is what I have:

let myUrl = '/this/is/some/url';
let splitUrl = myUrl.split('/').filter(v => v !== '');

splitUrl[2] = 'a';
let newUrl = splitUrl.join('/');

console.log(newUrl); // this/is/a/url

But now I wanted to change that into a RegEx so I came up with this:

const myUrl = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/[a-zA-Z0-9]/, 'a').replace(/^\//, '');

console.log(modifiedUrl); // ahis/is/some/url

But the result is not what I want since it outputs: ahis/is/some/url. I’ll admit that I am not so good with RegEx.

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

A few SO posts here and here did not help me since I still did not get how to replace only the content after the second forward slash.

Can I get some help?

>Solution :

You can use

let myUrl = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/\/((?:[^\/]*\/){2})[^\/]*/, '$1a');
console.log(modifiedUrl); // this/is/a/url

See this regex demo. Details:

  • \/ – a / char
  • ((?:[^\/]*\/){2}) – Group 1: two occurrences of any zero or more chars other than / + a / char
  • [^\/]* – zero or more chars other than /.

The replacement is the backreference to the Group 1 value + the new string that will be inserted in the resulting string.

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