I'm having trouble trying to find an item that has a hash (#), I want to change the hash in the url to another identifier. For example, I have a url like this => http://localhost:8088/stores/1/brands?q=# When searching with a hash, the url will change to something like this => http://localhost:8088/stores/1/brands?q=%23
How to replace like that and push it to current url?
let currentUrl = 'http://localhost:8088/stores/1/brands?q=#';
let url = new URL(currentUrl);
url.searchParams.set("q", "#"); // setting param
url.hash='';
let newUrl = url.href;
console.log(newUrl);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use replace
let currentUrl = "http://localhost:8088/stores/1/brands?q=#";
str = currentUrl.replace("#", "023");
console.log(str);
Update :
if you want to set the url you can use
location.href = str;
but in order to stop the infinite loop you need to add a extra para like
let currentUrl = "http://localhost:8088/stores/1/brands?q=#";
str = currentUrl.replace("#", "023");
console.log(str);
var hash = url.searchParams.get("hashset");
if(hash !== "1") {
console.log(str+"&hashset=1");
location.href = str+"&hashset=1";
} else {
console.log("hash already set")
}
You can use the function encodeURIComponent.
E.g.
encodeURIComponent("#") // gives %23
You can read the detail on MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent