Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
replacing the string values using grouping

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
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

You could use lookaheads to insert into the string without removing anything:

(?<!:|\/)(?=\/)|$

  • The (?<!:\/) is a negative lookbehind to ignore the protocol header (://)
  • The (?=\/) is a positive lookahead that checks for a single slash
  • The $ accounts for a string without a slash at the end

const regex = /(?<!:|\/)(?=\/)|$/;

const testString = 'http://stackoverflow.com/questions/1/replace-text';

console.log(testString.replace(regex, '/testing'))

about 4 years ago · Juan Pablo Isaza Report

0

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" )

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!