propertyParser.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Basic parser for URL properties
  3. * @author Miller Medeiros
  4. * @version 0.1.0 (2011/12/06)
  5. * MIT license
  6. */
  7. define(function(){
  8. var rProps = /([\w-]+)\s*:\s*(?:(\[[^\]]+\])|([^,]+)),?/g, //match "foo:bar" and "lorem:[ipsum,dolor]" capturing name as $1 and val as $2 or $3
  9. rArr = /^\[([^\]]+)\]$/; //match "[foo,bar]" capturing "foo,bar"
  10. function parseProperties(str){
  11. var match, obj = {};
  12. while (match = rProps.exec(str)) {
  13. obj[ match[1] ] = typecastVal(match[2] || match[3]);
  14. }
  15. return obj;
  16. }
  17. function typecastVal(val){
  18. if (rArr.test(val)){
  19. val = val.replace(rArr, '$1').split(',');
  20. } else if (val === 'null'){
  21. val = null;
  22. } else if (val === 'false'){
  23. val = false;
  24. } else if (val === 'true'){
  25. val = true;
  26. } else if (val === '' || val === "''" || val === '""'){
  27. val = '';
  28. } else if (! isNaN(val)) {
  29. //isNaN('') == false
  30. val = +val;
  31. }
  32. return val;
  33. }
  34. //API
  35. return {
  36. parseProperties : parseProperties,
  37. typecastVal : typecastVal
  38. };
  39. });