Skip to content

Instantly share code, notes, and snippets.

@twalker
Last active August 29, 2015 14:13
Show Gist options
  • Save twalker/8d24f2c5576cc3e27408 to your computer and use it in GitHub Desktop.
Save twalker/8d24f2c5576cc3e27408 to your computer and use it in GitHub Desktop.
Parses a string of semi-colon delimited options into a plain object.
/**
* parseAttrOptions
* Parses a string of semi-colon delimited options into a plain object.
*
* @example
* parseAttrOptions('align: center; width: 300; neat: true; yagni: [1,2,3]');
* >> {align: 'center', width: 300, neat: true, yagni: [1,2,3]}
*/
export default function parseAttrOptions(sOptions){
var opts = {};
if(!sOptions) return opts;
sOptions
.split(/;/)
.filter( pair => /.+:.+/.test(pair))
.map( pair => pair.split(/:/).map( p => p.trim()))
.filter( pair => pair.length === 2)
.forEach( pair => opts[pair[0]] = parseValue(pair[1]));
return opts
}
export function parseValue(s){
if(/^true$/i.test(s)) return true;
if(/^false$/i.test(s)) return false;
if(/^null$/i.test(s)) return null;
if(!isNaN(s)) return parseFloat(s);
// array values
if(/^\[(.*)\]$/.test(s)){
return s
.substring(1, s.length -1)
.split(',')
.map(v => v.trim())
.map(parseValue);
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment