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?

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.