A slug is usually a few words with each word separated by a delimiting character, usually an underscore or hyphen. A slugified version of the string “10 Tips to a Better Life!” would be “10-tips-to-a-better-life”. This function takes an arbitrary string and converts in for use as a slug. We use two regular expressions to accomplish this, the first is used to remove any character which is not a word character, space or hyphen, the second replaces any spaces with a single hyphen. Finally we convert the string to lowercase. This returns a new string, leaving the input string unchanged.
- function slugify(string:String):String
- const pattern1:RegExp = /[^\w- ]/g; // Matches anything except word characters, space and -
- const pattern2:RegExp = / +/g; // Matches one or more space characters
- var s:String = string;
- return s.replace(pattern1, "").replace(pattern2, "-").toLowerCase();
You need to login to post a comment.