Home > Software design >  How to change the hash (#) in the query string URL to another identifier with javascript?
How to change the hash (#) in the query string URL to another identifier with javascript?

Time:09-22

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=#

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>

CodePudding user response:

You can use the function encodeURIComponent.

E.g.

encodeURIComponent("#") // gives #

You can read the detail on MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

CodePudding user response:

you can use replace

let currentUrl = "http://localhost:8088/stores/1/brands?q=#";
str = currentUrl.replace("#", "023");
console.log(str);
  • Related