1

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?

Silve2611
  • 2,198
  • 2
  • 34
  • 55

2 Answers2

2

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Also another solution I found in Stackoverflow. How to replace all occurrences of a string in JavaScript?

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}
Community
  • 1
  • 1
Silve2611
  • 2,198
  • 2
  • 34
  • 55