輸入字串 "abcd1234",每 3 字元插入一空格 → "abc d12 34"。
function insertSpaceLoop(str, n = 3) {
let result = "";
for (let i = 0; i < str.length; i += n) {
result += str.slice(i, i + n) + " ";
}
return result.trimEnd(); // 移除尾部多餘空格
}
function insertSpaceRegex(str, n = 3) {
// (.{3}) 捕獲每 3 個字元,$1 回引用捕獲內容
return str.replace(new RegExp(`(.{${n}})`, "g"), "$1 ").trimEnd();
}
// 使用
insertSpaceRegex("abcd1234"); // "abc d12 34"
insertSpaceRegex("1234567890", 4); // "1234 5678 90"
(.{3}):捕獲組,匹配任意 3 字元(含換行需加 s 旗標)。g:全域匹配,依序處理所有捕獲組。$1:替換字串中引用第 1 個捕獲組的內容。trimEnd() 移除結尾多餘空格。function insertSpaceFlex(str, n = 3, separator = " ") {
return str.replace(new RegExp(`.{1,${n}}`, "g"), match => match + separator).trimEnd();
}
// 邊界情況:不足 n 字元的尾段也會被匹配(.{1,n}),自動加分隔符再 trim
insertSpaceFlex("abcde", 3); // "abc de"
function toThousands(numStr) {
// 從右向左每 3 位,使用正向前瞻
return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
toThousands("1234567890"); // "1,234,567,890"
function formatCard(numStr) {
return numStr.replace(/\s/g, "").replace(/(.{4})/g, "$1 ").trimEnd();
}
formatCard("1234 5678 9012 3456"); // "1234 5678 9012 3456"
// 匹配重複詞:\b(\w+)\s+\1\b
/\\b(\\w+)\\s+\\1\\b/.test("hello hello world"); // true
/\\b(\\w+)\\s+\\1\\b/.test("hello world"); // false
// 匹配成對標籤:<(\w+)>.*?\1>
/<(\w+)>.*?<\/\1>/.test("content"); // true
/<(\w+)>.*?<\/\1>/.test("content"); // false
效能提示
- 極長字串(>1MB)用
replace 可能較慢,改用 for 迴圈配合 StringBuilder 模式(陣列 push 最後 join)。
- 正則編譯有開銷,重複使用請提前建立
RegExp 物件或用字面量。
- 上一篇程序編程: AJAX 無刷新動態增刪表格列的完整實作範例
- 下一篇程序編程: 前後端 JSON 資料交換實作:JavaScript 與 PHP 串接指南