forked from sf-wdi-31/js-objects-training
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-string-parser.js
More file actions
57 lines (46 loc) · 1.55 KB
/
query-string-parser.js
File metadata and controls
57 lines (46 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Create a function `parseQueryString` that accepts a query string parameter as an argument, and
converts it into an object, using the following rules:
* An equals sign (`=`) separates a *key* on the left from a *value* on the right.
* An ampersand (`&`) separates key-value pairs from each other.
* All keys and values should be parsed as Strings.
* The query string will not contain spaces.
Here are some example inputs and outputs (mind the edge cases!):
```javascript
parseQueryString("");
//=> {}
parseQueryString("a=1");
//=> {
// "a": "1",
// }
parseQueryString("first=alpha&last=omega");
//=> {
// "first": "alpha",
// "last": "omega"
// }
parseQueryString("a=apple&b=beet&b=blueberry&c=&d=10");
//=> {
// "a": "apple",
// "b": "blueberry", // "blueberry" overwrites "beet"!
// "c": "", // empty string (missing value)
// "d": "10" // "10" is a String!
// }
```
Mega Bonus
- Can you create the reverse function? Given an object, output a Query Parameter String:
``` javascript
var o = {first: "alpha", last: "omega"};
convertToQueryParameter(o); // "first=alpha&last=omega";
```
*/
// YOUR CODE HERE
function parseQueryString(string) {
var obj = {};
stringArray = string.split("&");
for(var i=0; i < stringArray.length; i++) {
var key = stringArray[i].substring(0, stringArray[i].indexOf("="));
var value = stringArray[i].substring(stringArray[i].indexOf("=") + 1);
obj[key] = value;
}
return obj;
}