Tengo problemas para encontrar un elemento que tenga un hash (#), quiero cambiar el hash en la URL a otro identificador. Por ejemplo, tengo una url como esta => http://localhost:8088/stores/1/brands?q=# Al buscar con un hash, la url cambiará a algo como esto => http://localhost:8088/stores/1/brands?q=%23
¿Cómo reemplazar así y empujarlo a la URL actual?
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>puedes usar reemplazar
let currentUrl = "http://localhost:8088/stores/1/brands?q=#"; str = currentUrl.replace("#", "023"); console.log(str);Actualizar :
si quieres configurar la url puedes usar
location.href = str;pero para detener el ciclo infinito, debe agregar un párrafo adicional como
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") }Puede usar la función encodeURIComponent .
P.ej
encodeURIComponent("#") // gives %23Puede leer los detalles en los documentos de MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent