Obtener los parámetros pasados por get en una url usando vanilla js

Obtener parámetros de la url con js usando location

Para obtener los valores pasados en una url hay que hacer uso del objeto js window.location
La url a probar es la siguiente: http://localhost:400/?p1=v1&p2=value%202&p3=some$$%22%%&&strage%2099value

Objeto window.location
Objeto window.location
{ "ancestorOrigins": {}, "href": "http://localhost:400/?p1=v1&p2=value%202&p3=some$$%22%%&&strage%2099value", "origin": "http://localhost:400", "protocol": "http:", "host": "localhost:400", "hostname": "localhost", "port": "400", "pathname": "/", "search": "?p1=v1&p2=value%202&p3=some$$%22%%&&strage%2099value", "hash": "" } Si nos fijamos en el atributo search tenemos el string de parámetros.

La funcón getUrlParameter:

const getUrlParameter = name => { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]") const regex = new RegExp(`[\\?&]${name}=([^&#]*)`) const found = regex.exec(location.search) console.log("found:",found) let value = "" try { value = found === null ? "" : decodeURIComponent(found[1].replace(/\+/g, " ")) } catch (error) { console.log("error:",error) value = "" } return value }

Resultado ejecución

Ejecución función getUrlParameter
Ejecución función getUrlParameter

Autor: Eduardo A. F.
Publicado: 24-10-2021 13:10