Skip to content

Instantly share code, notes, and snippets.

@benmerckx
Last active May 7, 2019 23:57
Show Gist options
  • Save benmerckx/d2951ab4b15d88832117655b8b3f946c to your computer and use it in GitHub Desktop.
Save benmerckx/d2951ab4b15d88832117655b8b3f946c to your computer and use it in GitHub Desktop.
import hx.strings.Char;
import hx.strings.StringBuilder;
using hx.strings.Strings;
class Slug {
static final SEPARATE = [
Char.BACKSPACE,
Char.TAB,
Char.LF,
Char.CR,
Char.SPACE,
Char.EXCLAMATION_MARK,
Char.BRACKET_ROUND_LEFT,
Char.BRACKET_ROUND_RIGHT,
Char.COMMA,
Char.DOT,
Char.COLON,
Char.SLASH,
Char.SEMICOLON,
Char.LOWER_THAN,
Char.GREATER_THAN,
Char.QUESTION_MARK,
Char.UNDERSCORE,
Char.PIPE,
Char.BRACKET_CURLY_LEFT,
Char.BRACKET_CURLY_RIGHT,
Char.BACKSLASH,
Char.DOUBLE_QUOTE,
Char.ESC,
Char.HASH,
Char.SINGLE_QUOTE,
Char.ASTERISK
];
public static function slug(str: String, separator = '-'): String {
final parts: Array<String> = [];
final current = new StringBuilder();
for (char in str.toLowerCase8().toChars())
if (SEPARATE.indexOf(char) > -1) {
if (current.isEmpty()) continue;
parts.push(current.toString());
current.clear();
} else {
current.addChar(char);
}
if (!current.isEmpty()) parts.push(current.toString());
return parts.join(separator);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment