Split strings with regular expressions

0

Good I want to extract in separate strings a string with Jquery I do not know if to do it with regular expressions or some other method, the string is the following one

?i=0&edad=18_28&tarifa=40_80,81_110&servicio=25&ubicacion=1,4

Most of all extract the strings that are between the & amp; and save them in variables or array that is as follows:

id=0
edad=18_28
tarifa=40_48,81_110
servicio=25
ubicacion=1,4

Taking into account that they will not always be all of them sometimes, it may be age and rate but not location, please help

    
asked by Victor Laya 21.10.2018 в 01:35
source

1 answer

2

here is an example of how you can do it. You have different output formats so you can choose the most suitable for your case. Greetings!

const url = new URL('http://midominio.com/ruta/?param1=valor1&param2=valor2&param3=valor3')



const searchParams = url.searchParams

const keys = [...searchParams.keys()]

const object1 = keys
  .reduce((obj, key) =>({...obj, [key]: searchParams.get(key) }), {})
  
const object2 = [...searchParams.entries()]
  .reduce((obj, [key, value]) => ({...obj, [key]: value }), {})

console.log(object1)
console.log(object2)

// [[key1, value1], ...]
console.log([...searchParams.entries()])
// [key1, key2, ...]
console.log([...searchParams.keys()])
// [value1, value2, ...]
console.log([...searchParams.values()])
    
answered by 21.10.2018 / 01:57
source