* 执行格式化 * @param text 原始文本
(text: string)
| 85 | * 执行格式化 |
| 86 | * @param text 原始文本 |
| 87 | */ |
| 88 | public static spacing(text: string): string { |
| 89 | if (!text || text.length <= 1) return text; |
| 90 | |
| 91 | // 如果没有中文,直接返回,节省性能 |
| 92 | if (!PanguSpacer.ANY_CJK.test(text)) { |
| 93 | return text; |
| 94 | } |
| 95 | |
| 96 | // 保护 URL:简单的 URL 保护,避免破坏链接 |
| 97 | // 将 URL 替换为占位符 -> 处理文本 -> 还原 URL |
| 98 | const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g; |
| 99 | const urls: string[] = []; |
| 100 | let tempText = text.replace(urlRegex, (match) => { |
| 101 | urls.push(match); |
| 102 | return `\uFFFF${urls.length - 1}\uFFFF`; // 使用特殊字符作为占位符 |
| 103 | }); |
| 104 | |
| 105 | let newText = tempText; |
| 106 | |
| 107 | // CJK_QUOTE: CJK + " -> CJK + " " + " |
| 108 | newText = newText.replace(PanguSpacer.CJK_QUOTE, "$1 $2"); |
| 109 | // QUOTE_CJK: " + CJK -> " " + " + CJK |
| 110 | newText = newText.replace(PanguSpacer.QUOTE_CJK, "$1 $2"); |
| 111 | |
| 112 | newText = newText.replace(PanguSpacer.FIX_QUOTE_ANY_QUOTE, "$1$2$3"); |
| 113 | |
| 114 | // CJK_HASH: CJK + #word -> CJK + " " + #word |
| 115 | newText = newText.replace(PanguSpacer.CJK_HASH, "$1 $2"); |
| 116 | // HASH_CJK: word# + CJK -> word# + " " + CJK |
| 117 | newText = newText.replace(PanguSpacer.HASH_CJK, "$1 $3"); |
| 118 | |
| 119 | // CJK_ANS: CJK + ANS -> CJK + " " + ANS |
| 120 | newText = newText.replace(PanguSpacer.CJK_ANS, "$1 $2"); |
| 121 | // ANS_CJK: ANS + CJK -> ANS + " " + CJK |
| 122 | newText = newText.replace(PanguSpacer.ANS_CJK, "$1 $2"); |
| 123 | |
| 124 | // CJK_BRACKET: CJK + ( -> CJK + " " + ( |
| 125 | newText = newText.replace(PanguSpacer.CJK_BRACKET, "$1 $2"); |
| 126 | // BRACKET_CJK: ) + CJK -> ) + " " + CJK |
| 127 | newText = newText.replace(PanguSpacer.BRACKET_CJK, "$1 $2"); |
| 128 | |
| 129 | newText = newText.replace(PanguSpacer.FIX_BRACKET_ANY_BRACKET, "$1$3$5"); |
| 130 | |
| 131 | newText = newText.replace(PanguSpacer.CJK_ANS_CJK, "$1 $2 $3"); |
| 132 | newText = newText.replace(PanguSpacer.ANS_CJK_ANS, "$1 $2 $3"); |
| 133 | |
| 134 | // 还原 URL |
| 135 | newText = newText.replace(/\uFFFF(\d+)\uFFFF/g, (_, index) => { |
| 136 | return urls[parseInt(index)]; |
| 137 | }); |
| 138 | |
| 139 | return newText; |
| 140 | } |
| 141 | } |
| 142 | // ========================================== |
no outgoing calls
no test coverage detected