文字 Slugify(URL)
將文本規範化為 URL 友好的 slug,支援小寫、分隔符、自訂移除停用詞。
常見問題
Q: 中文字符會怎麼處理?
A: 預設會移除音標後保留拼音字母。純中文可能變為空字串,建議先手動轉為拼音再進行 slugify,或使用中文拼音轉換工具。
Q: 為什麼我的結果是空的?
A: 可能輸入全為標點符號/空格,或啟用停用詞過濾後無剩餘單詞。請嘗試關閉停用詞選項或調整輸入內容。
Q: 分隔符應該用 - 還是 _?
A: SEO 推薦使用 -(連字號),Google 會將其視為空格;_(底線)會被視為連接符,不利於分詞。檔案名可自由選擇。
Q: Slug 有長度限制嗎?
A: 技術上沒有限制,但建議保持在 50 個字元以內,以利 URL 顯示與 SEO。過長的 slug 可能被搜尋引擎截斷。
如何透過程式語言產生 Slug?
JavaScript
function slugify(text) {
return text
.toLowerCase()
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
}
PHP
function slugify($text) {
$text = mb_strtolower($text);
$text = iconv("UTF-8", "ASCII//TRANSLIT", $text);
$text = preg_replace("/[^\w\s-]/", "", $text);
$text = preg_replace("/[\s_-]+/", "-", $text);
return trim($text, "-");
}
Python
import re
import unicodedata
def slugify(text):
text = text.lower()
text = unicodedata.normalize("NFKD", text)
text = text.encode("ascii", "ignore").decode("ascii")
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"[\s_-]+", "-", text)
return text.strip("-")
Go
import (
"regexp"
"strings"
"golang.org/x/text/unicode/norm"
)
func Slugify(text string) string {
text = strings.ToLower(text)
text = norm.NFKD.String(text)
re := regexp.MustCompile(`[^\w\s-]`)
text = re.ReplaceAllString(text, "")
re = regexp.MustCompile(`[\s_-]+`)
text = re.ReplaceAllString(text, "-")
return strings.Trim(text, "-")
}
Ruby
require "unicode"
def slugify(text)
text = text.downcase
text = Unicode.nfkd(text).gsub(/[^\x00-\x7F]/, "")
text = text.gsub(/[^\w\s-]/, "")
text = text.gsub(/[\s_-]+/, "-")
text.strip.gsub(/^-+|-+$/, "")
end
Java
import java.text.Normalizer;
public static String slugify(String text) {
text = text.toLowerCase();
text = Normalizer.normalize(text, Normalizer.Form.NFKD);
text = text.replaceAll("[^\\w\\s-]", "");
text = text.replaceAll("[\\s_-]+", "-");
return text.replaceAll("^-+|-+$", "");
}