Puedo cambiar la última parte (en la URL: child ) de la URL, pero si los parámetros de la URL existen, estos parámetros se eliminan con este cambio ( ?para=1¶=2 ).
¿Hay alguna manera de no borrar los parámetros?
Muestra:
https://example.com/sub/child?para=1¶=2JS:
const str = window.location.href; const lastIndex = str.lastIndexOf("/"); const path = str.substring(0, lastIndex); const new_path = path + "/new_child"; window.history.pushState("object or string", "Title", new_path); window.history.replaceState("object or string", "Title", new_path);Antes de reemplazar la última parte, puede guardar los parámetros de esta manera
var str = "https://example.com/sub/child?para=1¶=2"; var params = str.split('?')[1] const lastIndex = str.lastIndexOf("/"); const path = str.substring(0, lastIndex); const new_path = path + "/new_child?"+params; console.log(new_path)Alternativamente, puede crear una función para hacer esto usando expresiones regulares
var str = "https://example.com/sub/child?para=1¶=2"; const new_path = replaceUrlPart(str, "child", "new_child") console.log(new_path) function replaceUrlPart(url, partToRemove, partToAdd){ return url.replace(partToRemove,partToAdd); }