StrUtils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* globals JsDiff */
  2. /**
  3. * String utility operations.
  4. *
  5. * @author n1474335 [n1474335@gmail.com]
  6. * @copyright Crown Copyright 2016
  7. * @license Apache-2.0
  8. *
  9. * @namespace
  10. */
  11. var StrUtils = {
  12. /**
  13. * @constant
  14. * @default
  15. */
  16. REGEX_PRE_POPULATE: [
  17. {
  18. name: "User defined",
  19. value: ""
  20. },
  21. {
  22. name: "IPv4 address",
  23. value: "(?:(?:\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d|\\d)(?:\\/\\d{1,2})?"
  24. },
  25. {
  26. name: "IPv6 address",
  27. value: "((?=.*::)(?!.*::.+::)(::)?([\\dA-Fa-f]{1,4}:(:|\\b)|){5}|([\\dA-Fa-f]{1,4}:){6})((([\\dA-Fa-f]{1,4}((?!\\3)::|:\\b|(?![\\dA-Fa-f])))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})"
  28. },
  29. {
  30. name: "Email address",
  31. value: "(\\w[-.\\w]*)@([-\\w]+(?:\\.[-\\w]+)*)\\.([A-Za-z]{2,4})"
  32. },
  33. {
  34. name: "URL",
  35. value: "([A-Za-z]+://)([-\\w]+(?:\\.\\w[-\\w]*)+)(:\\d+)?(/[^.!,?;\"\\x27<>()\\[\\]{}\\s\\x7F-\\xFF]*(?:[.!,?]+[^.!,?;\"\\x27<>()\\[\\]{}\\s\\x7F-\\xFF]+)*)?"
  36. },
  37. {
  38. name: "Domain",
  39. value: "(?:(https?):\\/\\/)?([-\\w.]+)\\.(com|net|org|biz|info|co|uk|onion|int|mobi|name|edu|gov|mil|eu|ac|ae|af|de|ca|ch|cn|cy|es|gb|hk|il|in|io|tv|me|nl|no|nz|ro|ru|tr|us|az|ir|kz|uz|pk)+"
  40. },
  41. {
  42. name: "Windows file path",
  43. value: "([A-Za-z]):\\\\((?:[A-Za-z\\d][A-Za-z\\d\\- \\x27_\\(\\)]{0,61}\\\\?)*[A-Za-z\\d][A-Za-z\\d\\- \\x27_\\(\\)]{0,61})(\\.[A-Za-z\\d]{1,6})?"
  44. },
  45. {
  46. name: "UNIX file path",
  47. value: "(?:/[A-Za-z\\d.][A-Za-z\\d\\-.]{0,61})+"
  48. },
  49. {
  50. name: "MAC address",
  51. value: "[A-Fa-f\\d]{2}(?:[:-][A-Fa-f\\d]{2}){5}"
  52. },
  53. {
  54. name: "Date (yyyy-mm-dd)",
  55. value: "((?:19|20)\\d\\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])"
  56. },
  57. {
  58. name: "Date (dd/mm/yyyy)",
  59. value: "(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((?:19|20)\\d\\d)"
  60. },
  61. {
  62. name: "Date (mm/dd/yyyy)",
  63. value: "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]((?:19|20)\\d\\d)"
  64. },
  65. {
  66. name: "Strings",
  67. value: "[A-Za-z\\d/\\-:.,_$%\\x27\"()<>= !\\[\\]{}@]{4,}"
  68. },
  69. ],
  70. /**
  71. * @constant
  72. * @default
  73. */
  74. REGEX_CASE_INSENSITIVE: true,
  75. /**
  76. * @constant
  77. * @default
  78. */
  79. REGEX_MULTILINE_MATCHING: true,
  80. /**
  81. * @constant
  82. * @default
  83. */
  84. OUTPUT_FORMAT: ["Highlight matches", "List matches", "List capture groups", "List matches with capture groups"],
  85. /**
  86. * @constant
  87. * @default
  88. */
  89. DISPLAY_TOTAL: false,
  90. /**
  91. * Regular expression operation.
  92. *
  93. * @param {string} input
  94. * @param {Object[]} args
  95. * @returns {html}
  96. */
  97. runRegex: function(input, args) {
  98. var userRegex = args[1],
  99. i = args[2],
  100. m = args[3],
  101. displayTotal = args[4],
  102. outputFormat = args[5],
  103. modifiers = "g";
  104. if (i) modifiers += "i";
  105. if (m) modifiers += "m";
  106. if (userRegex && userRegex !== "^" && userRegex !== "$") {
  107. try {
  108. var regex = new RegExp(userRegex, modifiers);
  109. switch (outputFormat) {
  110. case "Highlight matches":
  111. return StrUtils._regexHighlight(input, regex, displayTotal);
  112. case "List matches":
  113. return Utils.escapeHtml(StrUtils._regexList(input, regex, displayTotal, true, false));
  114. case "List capture groups":
  115. return Utils.escapeHtml(StrUtils._regexList(input, regex, displayTotal, false, true));
  116. case "List matches with capture groups":
  117. return Utils.escapeHtml(StrUtils._regexList(input, regex, displayTotal, true, true));
  118. default:
  119. return "Error: Invalid output format";
  120. }
  121. } catch (err) {
  122. return "Invalid regex. Details: " + err.message;
  123. }
  124. } else {
  125. return Utils.escapeHtml(input);
  126. }
  127. },
  128. /**
  129. * @constant
  130. * @default
  131. */
  132. CASE_SCOPE: ["All", "Word", "Sentence", "Paragraph"],
  133. /**
  134. * To Upper case operation.
  135. *
  136. * @param {string} input
  137. * @param {Object[]} args
  138. * @returns {string}
  139. */
  140. runUpper: function (input, args) {
  141. var scope = args[0];
  142. switch (scope) {
  143. case "Word":
  144. return input.replace(/(\b\w)/gi, function(m) {
  145. return m.toUpperCase();
  146. });
  147. case "Sentence":
  148. return input.replace(/(?:\.|^)\s*(\b\w)/gi, function(m) {
  149. return m.toUpperCase();
  150. });
  151. case "Paragraph":
  152. return input.replace(/(?:\n|^)\s*(\b\w)/gi, function(m) {
  153. return m.toUpperCase();
  154. });
  155. case "All":
  156. /* falls through */
  157. default:
  158. return input.toUpperCase();
  159. }
  160. },
  161. /**
  162. * To Upper case operation.
  163. *
  164. * @param {string} input
  165. * @param {Object[]} args
  166. * @returns {string}
  167. */
  168. runLower: function (input, args) {
  169. return input.toLowerCase();
  170. },
  171. /**
  172. * @constant
  173. * @default
  174. */
  175. SEARCH_TYPE: ["Regex", "Extended (\\n, \\t, \\x...)", "Simple string"],
  176. /**
  177. * @constant
  178. * @default
  179. */
  180. FIND_REPLACE_GLOBAL : true,
  181. /**
  182. * @constant
  183. * @default
  184. */
  185. FIND_REPLACE_CASE : false,
  186. /**
  187. * @constant
  188. * @default
  189. */
  190. FIND_REPLACE_MULTILINE : true,
  191. /**
  192. * Find / Replace operation.
  193. *
  194. * @param {string} input
  195. * @param {Object[]} args
  196. * @returns {string}
  197. */
  198. runFindReplace: function(input, args) {
  199. var find = args[0].string,
  200. type = args[0].option,
  201. replace = args[1],
  202. g = args[2],
  203. i = args[3],
  204. m = args[4],
  205. modifiers = "";
  206. if (g) modifiers += "g";
  207. if (i) modifiers += "i";
  208. if (m) modifiers += "m";
  209. if (type === "Regex") {
  210. find = new RegExp(find, modifiers);
  211. } else if (type.indexOf("Extended") === 0) {
  212. find = Utils.parseEscapedChars(find);
  213. }
  214. return input.replace(find, replace, modifiers);
  215. // Non-standard addition of flags in the third argument. This will work in Firefox but
  216. // probably nowhere else. The purpose is to allow global matching when the `find` parameter
  217. // is just a string.
  218. },
  219. /**
  220. * @constant
  221. * @default
  222. */
  223. SPLIT_DELIM: ",",
  224. /**
  225. * @constant
  226. * @default
  227. */
  228. DELIMITER_OPTIONS: ["Line feed", "CRLF", "Space", "Comma", "Semi-colon", "Colon", "Nothing (separate chars)"],
  229. /**
  230. * Split operation.
  231. *
  232. * @param {string} input
  233. * @param {Object[]} args
  234. * @returns {string}
  235. */
  236. runSplit: function(input, args) {
  237. var splitDelim = args[0] || StrUtils.SPLIT_DELIM,
  238. joinDelim = Utils.charRep[args[1]],
  239. sections = input.split(splitDelim);
  240. return sections.join(joinDelim);
  241. },
  242. /**
  243. * Filter operation.
  244. *
  245. * @author Mikescher (https://github.com/Mikescher | https://mikescher.com)
  246. * @param {string} input
  247. * @param {Object[]} args
  248. * @returns {string}
  249. */
  250. runFilter: function(input, args) {
  251. var delim = Utils.charRep[args[0]],
  252. reverse = args[2];
  253. try {
  254. var regex = new RegExp(args[1]);
  255. } catch (err) {
  256. return "Invalid regex. Details: " + err.message;
  257. }
  258. var regexFilter = function(value) {
  259. return reverse ^ regex.test(value);
  260. };
  261. return input.split(delim).filter(regexFilter).join(delim);
  262. },
  263. /**
  264. * @constant
  265. * @default
  266. */
  267. DIFF_SAMPLE_DELIMITER: "\\n\\n",
  268. /**
  269. * @constant
  270. * @default
  271. */
  272. DIFF_BY: ["Character", "Word", "Line", "Sentence", "CSS", "JSON"],
  273. /**
  274. * Diff operation.
  275. *
  276. * @param {string} input
  277. * @param {Object[]} args
  278. * @returns {html}
  279. */
  280. runDiff: function(input, args) {
  281. var sampleDelim = args[0],
  282. diffBy = args[1],
  283. showAdded = args[2],
  284. showRemoved = args[3],
  285. ignoreWhitespace = args[4],
  286. samples = input.split(sampleDelim),
  287. output = "",
  288. diff;
  289. if (!samples || samples.length !== 2) {
  290. return "Incorrect number of samples, perhaps you need to modify the sample delimiter or add more samples?";
  291. }
  292. switch (diffBy) {
  293. case "Character":
  294. diff = JsDiff.diffChars(samples[0], samples[1]);
  295. break;
  296. case "Word":
  297. if (ignoreWhitespace) {
  298. diff = JsDiff.diffWords(samples[0], samples[1]);
  299. } else {
  300. diff = JsDiff.diffWordsWithSpace(samples[0], samples[1]);
  301. }
  302. break;
  303. case "Line":
  304. if (ignoreWhitespace) {
  305. diff = JsDiff.diffTrimmedLines(samples[0], samples[1]);
  306. } else {
  307. diff = JsDiff.diffLines(samples[0], samples[1]);
  308. }
  309. break;
  310. case "Sentence":
  311. diff = JsDiff.diffSentences(samples[0], samples[1]);
  312. break;
  313. case "CSS":
  314. diff = JsDiff.diffCss(samples[0], samples[1]);
  315. break;
  316. case "JSON":
  317. diff = JsDiff.diffJson(samples[0], samples[1]);
  318. break;
  319. default:
  320. return "Invalid 'Diff by' option.";
  321. }
  322. for (var i = 0; i < diff.length; i++) {
  323. if (diff[i].added) {
  324. if (showAdded) output += "<span class='hlgreen'>" + Utils.escapeHtml(diff[i].value) + "</span>";
  325. } else if (diff[i].removed) {
  326. if (showRemoved) output += "<span class='hlred'>" + Utils.escapeHtml(diff[i].value) + "</span>";
  327. } else {
  328. output += Utils.escapeHtml(diff[i].value);
  329. }
  330. }
  331. return output;
  332. },
  333. /**
  334. * @constant
  335. * @default
  336. */
  337. OFF_CHK_SAMPLE_DELIMITER: "\\n\\n",
  338. /**
  339. * Offset checker operation.
  340. *
  341. * @param {string} input
  342. * @param {Object[]} args
  343. * @returns {html}
  344. */
  345. runOffsetChecker: function(input, args) {
  346. var sampleDelim = args[0],
  347. samples = input.split(sampleDelim),
  348. outputs = [],
  349. i = 0,
  350. s = 0,
  351. match = false,
  352. inMatch = false,
  353. chr;
  354. if (!samples || samples.length < 2) {
  355. return "Not enough samples, perhaps you need to modify the sample delimiter or add more data?";
  356. }
  357. // Initialise output strings
  358. for (s = 0; s < samples.length; s++) {
  359. outputs[s] = "";
  360. }
  361. // Loop through each character in the first sample
  362. for (i = 0; i < samples[0].length; i++) {
  363. chr = samples[0][i];
  364. match = false;
  365. // Loop through each sample to see if the chars are the same
  366. for (s = 1; s < samples.length; s++) {
  367. if (samples[s][i] !== chr) {
  368. match = false;
  369. break;
  370. }
  371. match = true;
  372. }
  373. // Write output for each sample
  374. for (s = 0; s < samples.length; s++) {
  375. if (samples[s].length <= i) {
  376. if (inMatch) outputs[s] += "</span>";
  377. if (s === samples.length - 1) inMatch = false;
  378. continue;
  379. }
  380. if (match && !inMatch) {
  381. outputs[s] += "<span class='hlgreen'>" + Utils.escapeHtml(samples[s][i]);
  382. if (samples[s].length === i + 1) outputs[s] += "</span>";
  383. if (s === samples.length - 1) inMatch = true;
  384. } else if (!match && inMatch) {
  385. outputs[s] += "</span>" + Utils.escapeHtml(samples[s][i]);
  386. if (s === samples.length - 1) inMatch = false;
  387. } else {
  388. outputs[s] += Utils.escapeHtml(samples[s][i]);
  389. if (inMatch && samples[s].length === i + 1) {
  390. outputs[s] += "</span>";
  391. if (samples[s].length - 1 !== i) inMatch = false;
  392. }
  393. }
  394. if (samples[0].length - 1 === i) {
  395. if (inMatch) outputs[s] += "</span>";
  396. outputs[s] += Utils.escapeHtml(samples[s].substring(i + 1));
  397. }
  398. }
  399. }
  400. return outputs.join(sampleDelim);
  401. },
  402. /**
  403. * Parse escaped string operation.
  404. *
  405. * @param {string} input
  406. * @param {Object[]} args
  407. * @returns {string}
  408. */
  409. runParseEscapedString: function(input, args) {
  410. return Utils.parseEscapedChars(input);
  411. },
  412. /**
  413. * Adds HTML highlights to matches within a string.
  414. *
  415. * @private
  416. * @param {string} input
  417. * @param {RegExp} regex
  418. * @param {boolean} displayTotal
  419. * @returns {string}
  420. */
  421. _regexHighlight: function(input, regex, displayTotal) {
  422. var output = "",
  423. m,
  424. hl = 1,
  425. i = 0,
  426. total = 0;
  427. while ((m = regex.exec(input))) {
  428. // Add up to match
  429. output += Utils.escapeHtml(input.slice(i, m.index));
  430. // Add match with highlighting
  431. output += "<span class='hl"+hl+"'>" + Utils.escapeHtml(m[0]) + "</span>";
  432. // Switch highlight
  433. hl = hl === 1 ? 2 : 1;
  434. i = regex.lastIndex;
  435. total++;
  436. }
  437. // Add all after final match
  438. output += Utils.escapeHtml(input.slice(i, input.length));
  439. if (displayTotal)
  440. output = "Total found: " + total + "\n\n" + output;
  441. return output;
  442. },
  443. /**
  444. * Creates a string listing the matches within a string.
  445. *
  446. * @private
  447. * @param {string} input
  448. * @param {RegExp} regex
  449. * @param {boolean} displayTotal
  450. * @param {boolean} matches - Display full match
  451. * @param {boolean} captureGroups - Display each of the capture groups separately
  452. * @returns {string}
  453. */
  454. _regexList: function(input, regex, displayTotal, matches, captureGroups) {
  455. var output = "",
  456. total = 0,
  457. match;
  458. while ((match = regex.exec(input))) {
  459. total++;
  460. if (matches) {
  461. output += match[0] + "\n";
  462. }
  463. if (captureGroups) {
  464. for (var i = 1; i < match.length; i++) {
  465. if (matches) {
  466. output += " Group " + i + ": ";
  467. }
  468. output += match[i] + "\n";
  469. }
  470. }
  471. }
  472. if (displayTotal)
  473. output = "Total found: " + total + "\n\n" + output;
  474. return output;
  475. },
  476. };