-3

I have a URL as a string want to replace only the subdomian i.e. changing https://example1.com/home to https://example2.com/home. What is the most effective way to do this in Angular or pure JS?

2

1 Answer 1

1

The simplest would likely be to split it twice, assuming you don't know what the sub domain will be, and then replace the sub domain using replace().

With split('//')[1] you get all but the protocol, and split('.')[0] will give you the sub domain.

var url = "https://example1.com/home"
var new_sub = "example2";

console.log( url.replace( url.split('//')[1].split('.')[0], new_sub ) )


With a regex you can do this

var url = "https://example1.com/home"
var new_sub = "example2";

console.log( url.replace( url.split(/[\/\.]+/)[1], new_sub ) )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.