Skip to content

Instantly share code, notes, and snippets.

@GavinJaynes
Created April 7, 2015 10:39
Show Gist options
  • Save GavinJaynes/f6fab4cb7676cddab707 to your computer and use it in GitHub Desktop.
Save GavinJaynes/f6fab4cb7676cddab707 to your computer and use it in GitHub Desktop.
Changing strings in JS
// Slug maker
//===================================
function slugify (value) {
return value.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/_/g, '-') // Replace underscores with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
};
// Databasify
//===================================
function databasify (value) {
return value.toString().toLowerCase()
.replace(/ /g,"_") // Replace spaces with _
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/-/g, '_') // Replace dashed with _
.replace(/\_\_+/g, '_') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text;
};
// Humanify maker
//===================================
function humanify (value) {
return value.substring(0, 1).toUpperCase() + value.substring(1)
.replace(/\-/g, ' ') // Replace dash for space
.replace(/\_/g, ' ') // Replace underscores with space
.replace(/\s\s+/g, ' ' ) // Replace mulitple spaces with one
.replace(/[^a-z0-9\s]/gi, '');// Remove all non-word chars
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment