Reputation: 8589
I am trying to replace some characters on the fly but it is not working. Look, I have this code which replaces any characters that are not URL friendly. I mean, the user will be typing on an input to construct a 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
}
So for example when the user types a space, it should be replace with -
, like here:
.replace(/\s+/g, "-") // Replace spaces with -
But that's not working. I noticed this one works:
.replace(/&/g, "-and-") // Replace & with 'and'
But why not the rest of them? Any ideas?
This is the whole code:
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)}
/>
Upvotes: 0
Views: 702
Reputation: 2463
.replace(/\s+/g, "-")
This replacement converts space to hyphen(-)
.replace(/-+$/, "");
This replacement converts hyphen(-) back to ""
So at the end you are getting "" for every space
Upvotes: 1