id.mjs 939 B

12345678910111213141516171819202122232425262728
  1. const regex = /\sid="(\S+)"/g;
  2. const randomPrefix = "IconifyId" + Date.now().toString(16) + (Math.random() * 16777216 | 0).toString(16);
  3. let counter = 0;
  4. function replaceIDs(body, prefix = randomPrefix) {
  5. const ids = [];
  6. let match;
  7. while (match = regex.exec(body)) {
  8. ids.push(match[1]);
  9. }
  10. if (!ids.length) {
  11. return body;
  12. }
  13. const suffix = "suffix" + (Math.random() * 16777216 | Date.now()).toString(16);
  14. ids.forEach((id) => {
  15. const newID = typeof prefix === "function" ? prefix(id) : prefix + (counter++).toString();
  16. const escapedID = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  17. body = body.replace(
  18. // Allowed characters before id: [#;"]
  19. // Allowed characters after id: [)"], .[a-z]
  20. new RegExp('([#;"])(' + escapedID + ')([")]|\\.[a-z])', "g"),
  21. "$1" + newID + suffix + "$3"
  22. );
  23. });
  24. body = body.replace(new RegExp(suffix, "g"), "");
  25. return body;
  26. }
  27. export { replaceIDs };