Skip to content
Advertisement

JavaScript Regex find and replace multiple word with multiple word without using multiple replace function

I am using Angular7 and I want to change url defined in the environment file without concatenation.

So I have a string in my component like this.

"upload/document/:orgId/products/:productId"

I want to replace it with 2 ids using regex-only so I can get output like this. I do not want to use multiple replace calls.

 "/upload/document/101/products/99101"

Thanks in advance!.

Advertisement

Answer

After some hard-hit and trials, this can be achieved. although it is not as I want in a single call, it is performing all the required stuff.

let baseUrl= "upload/document/:orgId/products/:productId";
let mapper = {
               ':orgId': 101, 
               ':productId': 99101 
             };
let newUrl = baseUrl.replace(
                 /:orgId|:productId/gi, 
                 matched => mapper[matched]
             ) ;
console.log(newUrl);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement