Get URL Query String Data With JavaScript

In this guide, we will share a JavaScript example of how to get the URL query string data in your custom logic or use it to pre-fill other form fields.

// Helper for getting URL query string data
function get_url_query_string_data( options ) {
  // Prevent errors
  options = options || {};
  // Check URL parameters
  var vars = {},
    hash;
  // Try and catch errors
  try {
    // Set URL
    var url = options.url ? options.url : window.location.href;
    // Resolve Spaces
    url = url.replace( /\+/g, '%20' );
    // Get URL
    var href = decodeURI( url );
    // Fix space
    href = href.replace( /%2B/g, '+' );
    // If query string available
    if ( href.indexOf( '?' ) > -1 ) {
      // Get hash values
      var hashes = href.slice( href.indexOf( '?' ) + 1 ).split( '&' );
    } else {
			// Set empty array
      hashes = [];
    }
    // Map hash values
    for ( var i = 0; i < hashes.length; i++ ) {
      // Get value
      hash = hashes[ i ].split( '=' );
      // Set value
      vars[ hash[ 0 ] ] = hash[ 1 ];
    }
  } catch ( error ) {
    // Long on browser console
    console.log( error );
  }
  // Retrun hash map
  return options.key ? vars[ options.key ] : vars;
}

For any questions, please contact us - [email protected] or the Formyoula in-app chat 🙂