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;

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

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 =;
var pathArray = window.location.pathname.split( '/' );

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect