string format

Format a string with '{0}','{1}'...

目前為 2022-12-20 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/453846/1130256/string%20format.js

  1. // ==UserScript==
  2. // @name string format
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.0.2
  5. // @description Format a string with '{0}','{1}'...
  6. // @license Apache License 2.0
  7. // @author 捈荼
  8. // commented by ChatGPT
  9. // ==/UserScript==
  10.  
  11. (function () {
  12. "use strict";
  13. // Check if the String.prototype.format function is already defined
  14. if (String.prototype.format == undefined) {
  15. // Define a new function named string_format_V2_0_2
  16. let string_format_V2_0_2 = function () {
  17. // Get the arguments passed to the function
  18. let args = arguments;
  19. // Initialize a counter variable
  20. let cnt = 0;
  21. // Check if the string contains numbered placeholders ({0}, {1}, etc.)
  22. // If not, check if the string contains unnumbered placeholders ({})
  23. return this.match(/{(\d+)}/g) == null && this.match(/{}/g) != null ?
  24. // If the string contains unnumbered placeholders, replace them with the corresponding arguments
  25. this.replace(/{}/g, (match) => {
  26. // If the corresponding argument is defined, return it; otherwise, return the placeholder
  27. return typeof args[cnt] != 'undefined' ? args[cnt++] : match;
  28. }) :
  29. // If the string contains numbered placeholders, replace them with the corresponding arguments
  30. this.replace(/{(\d+)}/g, (match, number) => {
  31. // If the argument at the specified index is defined, return it; otherwise, return the placeholder
  32. return typeof args[number] != 'undefined' ? args[number] : match;
  33. });
  34. };
  35. // Add the new function as the String.prototype.format function
  36. String.prototype.format = string_format_V2_0_2;
  37. } else {
  38. // If the String.prototype.format function is already defined, check if it is the correct implementation
  39. if (String.prototype.format.name != 'string_format_V2_0_2') {
  40. // If the function is not the correct implementation, throw an error
  41. throw 'String.prototype.format defined.';
  42. }
  43. }
  44. })();