PHP's parse_str in JavaScript

Here’s what our current JavaScript equivalent to PHP's parse_str looks like.

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
module.exports = function parse_str (str, array) { // eslint-disable-line camelcase
// discuss at: http://locutus.io/php/parse_str/
// original by: Cagri Ekin
// improved by: Michael White (http://getsprink.com)
// improved by: Jack
// improved by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: stag019
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
// reimplemented by: stag019
// input by: Dreamer
// input by: Zaide (http://zaidesthings.com/)
// input by: David Pesta (http://davidpesta.com/)
// input by: jeicquest
// note 1: When no argument is specified, will put variables in global scope.
// note 1: When a particular argument has been passed, and the
// note 1: returned value is different parse_str of PHP.
// note 1: For example, a=b=c&d====c
// example 1: var $arr = {}
// example 1: parse_str('first=foo&second=bar', $arr)
// example 1: var $result = $arr
// returns 1: { first: 'foo', second: 'bar' }
// example 2: var $arr = {}
// example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', $arr)
// example 2: var $result = $arr
// returns 2: { str_a: "Jack and Jill didn't see the well." }
// example 3: var $abc = {3:'a'}
// example 3: parse_str('a[b]["c"]=def&a[q]=t+5', $abc)
// example 3: var $result = $abc
// returns 3: {"3":"a","a":{"b":{"c":"def"},"q":"t 5"}}
var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&')
var sal = strArr.length
var i
var j
var ct
var p
var lastObj
var obj
var undef
var chr
var tmp
var key
var value
var postLeftBracketPos
var keys
var keysLen
var _fixStr = function (str) {
return decodeURIComponent(str.replace(/\+/g, '%20'))
}
var $global = (typeof window !== 'undefined' ? window : global)
$global.$locutus = $global.$locutus || {}
var $locutus = $global.$locutus
$locutus.php = $locutus.php || {}
if (!array) {
array = $global
}
for (i = 0; i < sal; i++) {
tmp = strArr[i].split('=')
key = _fixStr(tmp[0])
value = (tmp.length < 2) ? '' : _fixStr(tmp[1])
while (key.charAt(0) === ' ') {
key = key.slice(1)
}
if (key.indexOf('\x00') > -1) {
key = key.slice(0, key.indexOf('\x00'))
}
if (key && key.charAt(0) !== '[') {
keys = []
postLeftBracketPos = 0
for (j = 0; j < key.length; j++) {
if (key.charAt(j) === '[' && !postLeftBracketPos) {
postLeftBracketPos = j + 1
} else if (key.charAt(j) === ']') {
if (postLeftBracketPos) {
if (!keys.length) {
keys.push(key.slice(0, postLeftBracketPos - 1))
}
keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos))
postLeftBracketPos = 0
if (key.charAt(j + 1) !== '[') {
break
}
}
}
}
if (!keys.length) {
keys = [key]
}
for (j = 0; j < keys[0].length; j++) {
chr = keys[0].charAt(j)
if (chr === ' ' || chr === '.' || chr === '[') {
keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1)
}
if (chr === '[') {
break
}
}
obj = array
for (j = 0, keysLen = keys.length; j < keysLen; j++) {
key = keys[j].replace(/^['"]/, '').replace(/['"]$/, '')
lastObj = obj
if ((key !== '' && key !== ' ') || j === 0) {
if (obj[key] === undef) {
obj[key] = {}
}
obj = obj[key]
} else {
// To insert new dimension
ct = -1
for (p in obj) {
if (obj.hasOwnProperty(p)) {
if (+p > ct && p.match(/^\d+$/g)) {
ct = +p
}
}
}
key = ct + 1
}
}
lastObj[key] = value
}
}
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/parse_str'). You could also require the strings module in full so that you could access strings.parse_str instead.

If you intend to target the browser, you can then use a module bundler such as Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Notes

  • When no argument is specified, will put variables in global scope. When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1var $arr = {} parse_str('first=foo&second=bar', $arr) var $result = $arr{ first: 'foo', second: 'bar' }
2var $arr = {} parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', $arr) var $result = $arr{ str_a: "Jack and Jill didn't see the well." }
3var $abc = {3:'a'} parse_str('a[b]["c"]=def&a[q]=t+5', $abc) var $result = $abc{"3":"a","a":{"b":{"c":"def"},"q":"t 5"}}

« More PHP strings functions