Skip to content Skip to sidebar Skip to footer

How To Replace Host Part Of A Url Using Javascript Regex

How to replace the host part of a URL using javascript regex. This can be any kind of URL with or without http. Assume this text is from the content of a json file. OldText: {

Solution 1:

You can use the URL function and set a new hostname:

var oldUrl = "http://host1.dev.local:8000/one/two";
var url = new URL(oldUrl);
url.hostname = 'example.com';
url.href //'http://example.com:8080/one/two'

Solution 2:

This could be achieved easily using:

varNewText = OldText.replace (/(https?:\/\/)(.*?)(:*)/g, '$1' + 'example.com' + '$3'); 

You are welcome to modify this with the best practice.

Solution 3:

I think this is completely doable using regex. Here's a small snippet for you, let me know if you want to add something else to it.

var urls = [
    {
      url: "http://local.something.com:85/auth/signin"
    }, 

    {
      url: "local.anything.com/auth/profile"
    }
];
for(var i in urls) {
  var newUrl = urls[i].url.replace(/(http:|)(^|\/\/)(.*?\/)/g, 'https://example.com/');
  console.log(newUrl);
}

I am assuming, from

without http

, you mean something like 'google.com'

Post a Comment for "How To Replace Host Part Of A Url Using Javascript Regex"