Silve2611 Silve2611 - 23 days ago 14
Javascript Question

Remove substring (URL) from a string (URL) with javascript

I am having problems removing the baseUrl from a Url.

I have to string

var baseUrl = 'https://www.stackoverflow.com';
var Url = 'https://www.stackoverflow.com/test/number/';
Url.replace(baseUrl, "");


Now i would expect the result to be
/test/number/
but it does not remove the first part of the string.

The Code is an example. I do not always know for sure if the baseUrl is a substring so I cannot cut the length.

Any Ideas?

Answer

You need to update the string by returning value of String#replace method since the method won't updates the string.

var baseUrl = 'https://www.stackoverflow.com';
var Url = 'https://www.stackoverflow.com/test/number/';
Url = Url.replace(baseUrl, "");

console.log(Url);


Using String#substring and String#indexOf methods.

var baseUrl = 'https://www.stackoverflow.com';
var Url = 'https://www.stackoverflow.com/test/number/';
var i = Url.indexOf(baseUrl);
Url = Url.substring(0,i) + Url.substring(i + baseUrl.length);

console.log(Url);

Comments