/https?:\/\/\S+/gi
const text = `訪問 https://example.com 頁面
或者 https://test.org/path?query=value
結尾 https://last.one`;
const regex = /https?:\/\/\S+/gi;
const matches = text.match(regex);
console.log(matches);
// 輸出:
// [ "https://example.com", "https://test.org/path?query=value", "https://last.one" ]
| 輸入文本 | 匹配結果 | 說明 |
|---|---|---|
| `https://a.com,https://b.com` | `https://a.com,https://b.com` | 逗號非空白,視為 URL 一部分 (可能需改進) |
| `https://a.com. | `https://a.com.` | 句號非空白,包含在內 (常見問題) |
| `(https://a.com)` | `https://a.com)` | 括號非空白 |
// 排除常見尾部標點 . , ; : ) ] } > " '
const regex = /https?:\/\/[^\s.,;:)\]>"']+/gi;
// 或使用負向前瞻
const regex2 = /https?:\/\/\S+(?=[\s.,;:)\]>"']|$)/gi;
但**完美的 URL 正則極其複雜** (RFC 3986),生產環境建議使用成熟庫 (如 `url-regex`, `linkifyjs`)。
原回答中的代碼有誤:
// 錯誤
var re= /https?:\/\/\S+(\s|\n)/gi;
// 會將尾部空白/換行**包含在匹配結果中**
// 正確
var re = /https?:\/\/\S+/gi;
// \S+ 自動在空白前停止,不包含邊界字符