Javascript - 正则表达式从标题中删除特殊字符
Posted
技术标签:
【中文标题】Javascript - 正则表达式从标题中删除特殊字符【英文标题】:Javascript - Regex expression to remove special characters from title 【发布时间】:2020-12-22 22:38:08 【问题描述】:我正在尝试从我的标题中删除特殊字符并将其转换为 url 模式。我可以通过使用 .replace 方法来完成此操作,例如:title.replace(/[^A-Za-z0-9\-/s]/g, " ");
当标题中有括号时,我遇到了问题。我可以删除括号,但它会在最后留下一个空白空间,然后我用 -
填充空白空间以创建 URL 架构,这给了我一些问题。
如何调整下面的代码以删除 (Cat and Dog) 周围的括号,以免在后面留下空格?
这是我当前代码当前发生的情况:"Pet Supplies Cat and Dog "
let title = "Pet Supplies (Cat and Dog)"
let cleanTitle = ""
cleanTitle = title.replace(/[^A-Za-z0-9\-/s]/g, " ");
cleanTitle = cleanTitle.toLowerCase();
cleanTitle = cleanTitle.replace(new RegExp(" ", "g"), "-");
cleanTitle = cleanTitle.replace("-and", "");
cleanTitle = cleanTitle.replace(new RegExp("---", "g"), "--");
cleanTitle = cleanTitle.replace(new RegExp("--", "g"), "-");
console.log(cleanTitle)
我的预期结果是:pet-supplies-cat-dog
【问题讨论】:
如果我的措辞不正确,您好抱歉。我对url-schema
的意思是,我将在我的页面上有一个文章标题,我将重新定向,因此我试图将任何标题转换为友好的 URL,例如 Pet Supplies (Cat and Dog)
到 website.com/pet-supplies-cat-dog
我认为您想要的称为slug
。有很多示例如何使用 javascript 生成这些示例,例如***.com/questions/1053902/….
您可以只使用trim
字符串,cleanTitle.toLowerCase();
=> cleanTitle.trim().toLowerCase();
。另外,您的意思是要将空格与/s
匹配吗?必须是\s
。
【参考方案1】:
你可以使用
let title = "Pet Supplies (Cat and Dog)"
title = title.toLowerCase() // Turn to lower
.match(/[a-z0-9\s-]+/g) // Extract all alnum + hyphen and whitespace chunks
.map(x => x.trim().split(/\s+/).join("-")) // Trim the items, split with whitespace and join with a hyphen
.join("-") // Join the items with a hyphen
.replace(/-and\b/g, ''); // Remove whole word -and
console.log(title);
【讨论】:
【参考方案2】:可能有更优雅的方法可以做到这一点,但您只想删除开头和结尾的特殊字符而不添加空格字符(或添加后将其删除)。这可以通过两个额外的替换来完成:
let title = "Pet Supplies (Cat and Dog)"
let cleanTitle = ""
cleanTitle = title.replace(/[^A-Za-z0-9\-/s]/g, " ");
cleanTitle = cleanTitle.replace(/^ /g, "");
cleanTitle = cleanTitle.replace(/ $/g, "");
cleanTitle = cleanTitle.toLowerCase();
cleanTitle = cleanTitle.replace(new RegExp(" ", "g"), "-");
cleanTitle = cleanTitle.replace("-and", "");
cleanTitle = cleanTitle.replace(new RegExp("---", "g"), "--");
cleanTitle = cleanTitle.replace(new RegExp("--", "g"), "-");
console.log(cleanTitle)
【讨论】:
【参考方案3】:你可以通过这种方式实现你的输出:
let title = "Pet Supplies (Cat and Dog)"
let cleanTitle = ""
cleanTitle = title.replace(/and/g,''); // removing all "and"
cleanTitle = cleanTitle.replace(/\s+/g, '-'); // replacing all spaces by "-"
cleanTitle = cleanTitle.replace(/([()])/g, ''); // removing all "()"
cleanTitle = cleanTitle.toLowerCase(); // converting to lowercases
console.log(cleanTitle)
【讨论】:
以上是关于Javascript - 正则表达式从标题中删除特殊字符的主要内容,如果未能解决你的问题,请参考以下文章