DeindentTemplateLiteralString

Exports a simple function that can be passed a template literal. It strips code indentation from it while preserving intended indentation, by stripping out the smallest indent every line has in common.

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

  1. // ==UserScript==
  2. // @name DeindentTemplateLiteralString
  3. // @license Unlicense
  4. // @namespace 1N07
  5. // @match *://*/*
  6. // @version 1.2
  7. // @author 1N07
  8. // @description Exports a simple function that can be passed a template literal. It strips code indentation from it while preserving intended indentation, by stripping out the smallest indent every line has in common.
  9. // ==/UserScript==
  10.  
  11. /**
  12. * Takes a string (usually evaluated from a template literal) and strips code indentation from it,
  13. * while preserving intended intendation, by slicing out the smallest indentation each line has in common.
  14. * @param {String} str
  15. * @returns str with code indentation removed
  16. */
  17. function DeindentTemplateLiteralString(str) {
  18. const smallestIndent = Math.min(
  19. ...str
  20. .split("\n")
  21. .filter((line) => line.trim())
  22. .map((line) => line.match(/^\s+/)?.[0]?.length),
  23. );
  24. return str
  25. .split("\n")
  26. .map((line) => line.slice(smallestIndent))
  27. .join("\n")
  28. .trim();
  29. }
  30.  
  31. //aliases
  32. const Deindent = DeindentTemplateLiteralString;

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址