We are receiving an input parameter value as a pipe-delimited key-value pair, separated with =
symbols. For example:
\"|User=0101|Name=ImNewUse
If you do decide to use regex, make sure it's block rockin' regex like this:
var result = {};
s.replace(/([^=|]+)=([^|]*)/g, function(noStep3, a, b) { result[a] = b; });
You don't need the outer pipes. If necessary, trim them off str.slice(1, str.length - 1)
const str = "User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235";
str.split('|').reduce((accum, x) => {
const kv = x.split('=');
return {...accum, ...{[kv[0]]: kv[1]}};
}, {})
Cleanest way possible, you can modify the source to split by a different delimiter.
https://gist.github.com/allensarkisyan/5873977#file-parsequerystring-js
`/**
* @name - parseQueryString
* @author - Allen Sarkisyan
* @license - Open Source MIT License
*
* @description - Parses a query string into an Object.
* - Optionally can also parse location.search by invoking without an argument
*/`
`
function parseQueryString(queryString) {
var obj = {};
function sliceUp(x) { x.replace('?', '').split('&').forEach(splitUp); }
function splitUp(x) { var str = x.split('='); obj[str[0]] = decodeURIComponent(str[1]); }
try { (!queryString ? sliceUp(location.search) : sliceUp(queryString)); } catch(e) {}
return obj;
}
`
I would just use regular expressions to group (see here) each KEY=VALUE
pair and then iterate over them to fill up the JSON object. So you could have something like this:
var re = /(([^=\|]+)=([^=\|]+))/g;
var match;
var myString = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
while (match = re.exec(myString)) {
console.log(match);
// first iteration returns ["User=0101","User=0101","User","0101"] and so on
}
var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
var result = {}, name;
str.substring(1, str.length-1).split(/\||=/).forEach(function(item, idx){
idx%2 ? (result[name] = item) : (name = item);
});
The first one sounds good:
var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
var result = {};
str.split('|').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});