Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

{
   "auth" : {
     "login" : "http://local.example.com:85/auth/signin",
     "resetpass" : "http://local.example.com:85/auth/resetpass",
     "profile" : "http://local.example.com/auth/profile"
   }
}

Expecting a solution like:

var NewText = OldText.replace (/(some regex)/g, 'example.com');

To get NewText as:

{
  "auth" : {
     "login" : "http://example.com:85/auth/signin",
     "resetpass" : "http://example.com:85/auth/resetpass",
     "profile" : "http://example.com/auth/profile"
    }
}

I found the same here, but that regex won't work in javascript.

Note: I'm looking for the Regex.

like image 771
sith Avatar asked Jan 11 '17 03:01

sith


2 Answers

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'
like image 122
hackerrdave Avatar answered Oct 02 '22 09:10

hackerrdave


This could be achieved easily using:

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

You are welcome to modify this with the best practice.

like image 39
sith Avatar answered Oct 02 '22 10:10

sith