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?
1 Answer
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 ) )
string.Replace()?