Skip to content
Advertisement

check query strings in URL and if query strings have a value in javascript (vue)

I have a form submitting using VUE.js and from my back end server I am receiving a response code which is a URL with query parameters. Now depending on the query parameters I will create some conditionals / logic. As of now I am getting the query paramaters, splitting them to create an array of the 3 and this is working so far so good. If I log the different fields as in my code I get the values:

example response: test-services.com/api/test.cfm?fto=&cd=544346024&hd=v259787196

from console : fto= cd=544346024 hd=v259787196

I am stuck here as to how to check if each of these parameters contains the number after the equals sign.

the end result is if each of these fields has a value or not create my logic

 const encodeResponseUrl = responseCode.slice(responseCode.indexOf('?') + 1)

              const splitResponseUrl = encodeResponseUrl.split('&')

              const ftoField = splitResponseUrl[0]
              const cdField = splitResponseUrl[1]
              const hdField = splitResponseUrl[2]

              console.log(ftoField, cdField, hdField)

Advertisement

Answer

You could just use the URL class to parse the full URL string, and then get to the URLSearchParams via url.searchParams:

const searchParams = new URL('https://test-services.com/api/test.cfm?fto=&cd=544346024&hd=v259787196').searchParams

console.log({
  fto: searchParams.get('fto'),
  cd: searchParams.get('cd'),
  hd: searchParams.get('hd'),
})

You can then determine whether a specific field has a value by checking the result of searchParams.get() (if it’s falsy, then no value is specified).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement