I do something exactly like this in my own application. There is some server side code to it as well which is used to validate the generated value, but I have created a JavaScript helper to do a client-side "Urlify". It will replace ' ', ':', '\', and '/' with a '-', then remove all non-alpha-numeric characters, and finally clean up any instances of more than 1 '-' side-by-side.
function FormatForUrl(str) {
return str.replace(/_/g, '-')
.replace(/ /g, '-')
.replace(/:/g, '-')
.replace(/\\/g, '-')
.replace(/\//g, '-')
.replace(/[^a-zA-Z0-9\-]+/g, '')
.replace(/-{2,}/g, '-')
.toLowerCase();
};
Examples
- "Hello World" - "hello-world"
- "The car cost $1700" - "the-car-cost-1700"
- "Hey, let's go to the corner-store." - "hey-lets-go-to-the-corner-store"
- "www.mywebsite.com/page1.html" - "wwwmywebsitecom-page1html"
- "[email protected]" - "emailmywebsitecom"