I have url string, where i want insert one string and stitch it back together. I am able to add the first two set of strings but the last group I am not able to
let string = 'http://stackoverflow.com/questions/1/replace-text'
.replace(/(\/\/[^\/]+)?\/.*/, '$1/testing/$2');
console.log(string)
Here I want to attach the remaining part after the first slash which should be $2 but I am not able to achieve it. How can I achieve this what my expected output is
http://stackoverflow.com/testing/questions/1/replace-text
You don't need to match the rest of the URL. Just match the part you want to replace, and the rest will be kept in the replacement.
let string = 'http://stackoverflow.com/questions/1/replace-text'
.replace(/\/\/[^\/]+/, '$&/testing');
console.log(string)
You could use lookaheads to insert into the string without removing anything:
(?<!:|\/)(?=\/)|$
(?<!:\/) is a negative lookbehind to ignore the protocol header (://)(?=\/) is a positive lookahead that checks for a single slash$ accounts for a string without a slash at the endconst regex = /(?<!:|\/)(?=\/)|$/;
const testString = 'http://stackoverflow.com/questions/1/replace-text';
console.log(testString.replace(regex, '/testing'))
Not quite a fancy solution but it works.
let string = 'http://stackoverflow.com/questions/1/replace-text'
// http://stackoverflow.com/testing/questions/1/replace-text
let parts = string.split("/")
let newString = parts[0] + "//"+ parts[2] + "/testing/" + parts[3] +"/" + parts[4] + "/" + parts[5]
console.log( newString , "newString" )