1

I am writing a function that detects if the current URL contains a certain substring. If it contains, then I would like to remove it.

For example,

localhost/4000?ab=2&item=google

localhost/4000?ab=2&item=google123

localhost/4000?ab=2&item=google1233&haha=helpful

My idea is below....but kinda stuck in the process

function changeUrl(item) {

    var currentUrl = window.location.href; 
        if(currentUrl.includes('&item=') ){
        .....
        .....
        return currentUrl 

    }else return; 
}
1

2 Answers 2

1

I wouldn't try to manipulate it as a string. JavaSccript has a perfectly good tool to manipulate URLs, and you might as well use it:

str = 'http://localhost/4000?ab=2&item=google1233&haha=helpful';
url = new URL(str);
url.searchParams.delete('item'); // Idempotent call
result = url.toString();
Sign up to request clarification or add additional context in comments.

4 Comments

This is what I need !, May I know what Idempotent call is? I google a bit but still don't get a good explanation with regard to this context
Without getting too formal, "idempotent" means that the function will produce the result regardless of the state of the input. Here, after calling url.searchParams.delete('item') you are sure that the searchParams don't contain "item" regardless of whether it was present before the call or not. In other words, you don't need to bother checking if it's there, you can just call delete either way.
So basically, in this case, it free you from the worry if this call will break when actually there is no such item, right?
@hose yup, exactly
0

In this case, it's better to use URLSearchParams. MDN DOCS

The URLSearchParams interface defines utility methods to work with the query string of a URL.

var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);

// you can see params by this way
for (let p of params) {
  console.log(p);
}

// if you want to check if some params are exist
console.log(params.has('foo')); // true

// if you want to delete some params
console.log(params.toString());
params.delete('foo');
console.log(params.toString());

Comments

Your Answer

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