Skip to content

Instantly share code, notes, and snippets.

@marcusandre
Last active December 14, 2015 06:09
Show Gist options
  • Save marcusandre/5040236 to your computer and use it in GitHub Desktop.
Save marcusandre/5040236 to your computer and use it in GitHub Desktop.
Generate a slug with JavaScript.
// sync example.
function createSlug(title) {
return title
.toLowerCase()
.replace(/[^\w ]+/g,'')
.replace(/ +/g,'-');
}
var slug = createSlug('This is a test!');
console.log(slug);
// Or some kind of async...
function createSlug(title, callback) {
if (typeof title == 'string') {
var slug = title
.toLowerCase()
.replace(/[^\w ]+/g,'')
.replace(/ +/g,'-');
return callback(null, slug);
} else {
return callback('Title is no string', null);
}
}
createSlug('This is a test', function(err, slug) {
if (err) {
throw new Error(err);
} else {
console.log(slug);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment