Get base url in javascript

If you are constructing your URL like this;

message += '<br><a href=/Project/GetFileData?documentId=' + response.Data.vm.DocumentId + '>' + response.Data.vm.FileName + '</a>';

You will get results like this;

https://www.foo.com/Project/GetFileData?1234

This will not work on a web site that has following URL;

https://www.foo.com/demo/Project/GetFileData?1234

To fix this problem in ASP.NET Core, use this;

var url = '@Url.Content("~");
message += '<br><a href=' + url + '/Project/GetFileData?documentId=' + response.Data.vm.DocumentId + '>' + response.Data.vm.FileName + '</a>';

Other useful function to find URL are;

var url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect