0

I have a string returned from php ajax page like this:

$returnString = "firstName=" . $row['firstName'] . "&lastName=" 
  .$row['lastName'] . "&address=" . $row['address'] . "&province_id=" 
  .$row['province_id'] . "&city_id=" . $row['city_id'];

so on my calling page I get the string returned to :

var newCompleteString = this.responseText;

I am trying to figure out the best way to parse the string into a key: value array

Blag
  • 5,818
  • 2
  • 22
  • 45
DaleG
  • 11
  • 2
  • Is this what you want? http://stackoverflow.com/q/901115/340760 – BrunoLM Jan 08 '17 at 23:22
  • Split from `&` that will build an array for each something=value. You can then loop through them and split them from `=` creating a new array. `array[0]` will = to the property and `array[1]` will = to the value – NewToJS Jan 08 '17 at 23:22
  • Example - https://jsfiddle.net/wgzrss0d/ – NewToJS Jan 08 '17 at 23:35

1 Answers1

0

What you want seems to be basically the same as parsing the query string.

See this question How can I get query string values in JavaScript?

const getParams = query => {
  if (!query) {
    return { };
  }

  return (/^[?#]/.test(query) ? query.slice(1) : query)
    .split('&')
    .reduce((params, param) => {
      let [ key, value ] = param.split('=');
      params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
      return params;
    }, { });
};

console.log(
  getParams('firstName=first&lastName=last&address=addr&province_id=322&city_id=11')
);
Community
  • 1
  • 1
BrunoLM
  • 97,872
  • 84
  • 296
  • 452