args-parser.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Arguments parser for custom tag
  3. */
  4. export class ArgsParser {
  5. /**
  6. * @typedef ParseArgsResult
  7. * @property {string} firstArgsKey - key of the first argument
  8. * @property {string|boolean} firstArgsValue - value of the first argument
  9. * @property {object} options - key of the first argument
  10. */
  11. /**
  12. * parse plugin argument strings
  13. *
  14. * @static
  15. * @param {string} str
  16. * @returns {ParseArgsResult}
  17. */
  18. static parse(str) {
  19. let firstArgsKey = null;
  20. let firstArgsValue = null;
  21. const options = {};
  22. if (str != null && str.length > 0) {
  23. const splittedArgs = str.split(',');
  24. splittedArgs.forEach((rawArg, index) => {
  25. const arg = rawArg.trim();
  26. // parse string like 'key1=value1, key2=value2, ...'
  27. // see https://regex101.com/r/pYHcOM/1
  28. const match = arg.match(/([^=]+)=?(.+)?/);
  29. if (match == null) {
  30. return;
  31. }
  32. const key = match[1];
  33. const value = match[2] || true;
  34. options[key] = value;
  35. if (index === 0) {
  36. firstArgsKey = key;
  37. firstArgsValue = value;
  38. }
  39. });
  40. }
  41. return {
  42. firstArgsKey,
  43. firstArgsValue,
  44. options,
  45. };
  46. }
  47. }