【发布时间】:2020-09-22 11:41:00
【问题描述】:
我正在尝试动态替换一些字符,但它不起作用。 看,我有这个代码可以替换任何不友好的 URL 字符。我的意思是,用户将在输入中输入以构建 URL:
function slugify(string) {
const a =
"àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;";
const b =
"aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------";
const p = new RegExp(a.split("").join("|"), "g");
return string
.toString()
.toLowerCase()
.replace(/\s+/g, "-") // Replace spaces with -
.replace(p, (c) => b.charAt(a.indexOf(c))) // Replace special characters
.replace(/&/g, "-and-") // Replace & with 'and'
.replace(/[^\w\-]+/g, "") // Remove all non-word characters
.replace(/\-\-+/g, "-") // Replace multiple - with single -
.replace(/^-+/, "") // Trim - from start of text
.replace(/-+$/, ""); // Trim - from end of text
}
所以例如当用户输入一个空格时,它应该被替换为-,就像这里:
.replace(/\s+/g, "-") // Replace spaces with -
但这不起作用。我注意到这个有效:
.replace(/&/g, "-and-") // Replace & with 'and'
但为什么不是其他人呢?有什么想法吗?
这是整个代码:
const handleSiteUrl = (value) => {
setNameToUrlAction({
...nameToUrl,
siteUrl: slugify(value.toLowerCase()), // HERE I USE slugify METHOD
});
};
<input
id="siteUrl"
name="siteUrl"
className="form-control"
placeholder="Enter name"
value={`/${nameToUrl.siteUrl}`}
onChange={(e) => handleSiteUrl(e.target.value)}
/>
【问题讨论】:
-
@YannickK 我在问题中发布了用户键入应该用连字符替换的空格的场景,但这并没有发生。很好的预期输出是,当用户输入空格时,我需要设置一个连字符。
标签: javascript regex reactjs redux ecmascript-6