-2

I would like to split string if & character is showing but it must ignore the split if & shows in the beginning of the string. example '&hello=world&hi=usa' would be

key: &hello, value: world
key: hi, value: usa

if i use split('&') it will create empty key and value because of the first &

deals4us3
  • 35
  • 1
  • 4

1 Answers1

-1

You can simply remove the empty item from the array generated by the split() function:

let s = '&hello=world&hi=usa';

let a = s.split("&");
if (a[0] == "") {
  a.shift(0);
}
let arr = [];

for (let i = 0; i < a.length; i++) {
  let n = a[i].split("=");
  let k = n[0];
  let v = n[1];
  arr.push({"key": k, "value": v});
}

console.log(arr);
ATD
  • 1,344
  • 1
  • 4
  • 8