Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Created December 21, 2021 19:36
Show Gist options
  • Save D1360-64RC14/5d7f1c7676c8506df7040b1d93f51cc1 to your computer and use it in GitHub Desktop.
Save D1360-64RC14/5d7f1c7676c8506df7040b1d93f51cc1 to your computer and use it in GitHub Desktop.
Implementation of proper FormURLEncoded class in JS
class FormURLEncoded extends Map {
/**
* @param {Nullable<String>} formString - Form URL encoded string (ex: `'hello=world&foo=bar&tar=gz'`)
*/
constructor(formString = null) {
super(formString ?
formString
.trim()
.split('&')
.map(
element => element.split('=').map(decodeURIComponent)
)
: undefined
);
}
/**
* Translate the Map to a form URL encoded string
* @returns {String}
*/
toString() {
return Array.from(this)
.map(
element => element.map(encodeURIComponent).join('=')
)
.join('&')
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment