ParseUtil

Utility methods for DOM and string parsing

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/391979/746751/ParseUtil.js

  1. // ==UserScript==
  2. // @name ParseUtil
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.2
  5. // @description Utility methods for DOM and string parsing
  6. // @author Gerrit Höhle
  7. // @grant GM_xmlhttpRequest
  8. // ==/UserScript==
  9.  
  10. /* jshint esnext: true */
  11. const ParseUtil = {
  12. getPageAsync: (url, onSuccess, onError = () => {}) => {
  13. return GM_xmlhttpRequest({
  14. method: 'GET',
  15. url: url,
  16. onload: (resp) => {
  17. resp.html = new DOMParser().parseFromString(resp.responseText || "", 'text/html');
  18. switch (resp.status) {
  19. case 200:
  20. case 304:
  21. onSuccess(resp);
  22. return;
  23. default:
  24. onError(resp);
  25. return;
  26. }
  27. },
  28. onerror: onError
  29. });
  30. },
  31.  
  32. parseInt: (str, maxIntPlaces = 1, fallbackValue = null) => {
  33. let regex = "\\d";
  34. if (maxIntPlaces > 1) {
  35. regex += "{1," + maxIntPlaces + "}";
  36. }
  37. return ParseUtil.parseIntWithRegex(str, new RegExp(regex), fallbackValue);
  38. },
  39.  
  40. parseFloat: (str, maxIntPlaces = 1, maxDecPlaces = 0, fallbackValue = null) => {
  41. let regex = "\\d";
  42. if (maxIntPlaces > 1) {
  43. regex += "{1," + maxIntPlaces + "}";
  44. }
  45. if (maxDecPlaces > 0) {
  46. regex += "\\s?[,\.]?\\s?\\d{0," + maxDecPlaces + "}";
  47. }
  48. return ParseUtil.parseFloatWithRegex(str, new RegExp(regex), fallbackValue);
  49. },
  50.  
  51. parseIntWithRegex: (str, regex, fallbackValue = null) => {
  52. const match = ParseUtil.parseStrWithRegex(str, regex);
  53. const value = parseInt(match);
  54. return Number.isNaN(value) ? fallbackValue : value;
  55. },
  56.  
  57. parseFloatWithRegex: (str, regex, fallbackValue = null) => {
  58. const match = ParseUtil.parseStrWithRegex(str, regex, "").replace(",",".");
  59. const value = parseFloat(match);
  60. return Number.isNaN(value) ? fallbackValue : value;
  61. },
  62.  
  63. parseStrWithRegex: (str, regex, fallbackValue = null) => {
  64. const match = regex.exec(str || "");
  65. return (match && match.length >= 1) ? match[0] : fallbackValue;
  66. }
  67. };