JSFiddle - React, Tailwind, and code Playground
by stevelove
JavaScript
// Matches everything that is NOT A-Z, a-z or 0-9
// Also leaves spaces to replace later
var bad_characters = /[^A-Za-z0-9\s]/g;
// The dirty string
var dirty = " t!@h#i$s %i-s^&—) ({i]/t>,.@= ¥ 123_+test ";
// Remove the bad characters
var clean = dirty.replace(bad_characters, "");
// Trim right and left whitespace
var trimmed = clean.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
// Replace remaining whitespace with hyphens
var hyphenated = trimmed.replace(/\s+/g, "-");
console.log("Cleaned: " + clean);
console.log("Trimmed: " + trimmed);
console.log("Hyphenated: " + hyphenated);