The accepted answer didn't meet my needs (it allows underscores, doesn't handle dashes at the beginning and end, etc.), and the other answers had other issues that didn't suit my use case, so here's the slugify function I came up with:
function slugify(string) {
return string.trim() // Remove surrounding whitespace.
.toLowerCase() // Lowercase.
.replace(/[^a-z0-9]+/g,'-') // Find everything that is not a lowercase letter or number, one or more times, globally, and replace it with a dash.
.replace(/^-+/, '') // Remove all dashes from the beginning of the string.
.replace(/-+$/, ''); // Remove all dashes from the end of the string.
}
This will turn ' foo!!!BAR_-_-_baz-' (note the space at the beginning) into foo-bar-baz
.