[英]How to remove certain warning text from input value only when user starts typing in the input field?
[英]How can I replace certain character when a user is typing on an input field?
我正在嘗試即時替換一些字符,但它不起作用。 看,我有這個代碼可以替換任何不是 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'
但是為什么不是他們的 rest 呢? 有任何想法嗎?
這是整個代碼:
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)}
/>
.replace(/\s+/g, "-")
此替換將空格轉換為連字符 (-)
.replace(/-+$/, "");
此替換將連字符 (-)轉換回""
所以最后你會得到每個空間的“”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.