Slugify a String
Turn a title into a URL-friendly slug: lowercase, replace runs of non-alphanumeric characters with hyphens, and trim stray hyphens.
Sample input
Hello World! This is Test
Sample output
hello-world-this-is-test
Solution
import re
s = "Hello World! This is Test"
slug = re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")
print(slug)
const s = "Hello World! This is Test";
const slug = s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
console.log(slug);
public class Main {
public static void main(String[] args) {
String s = "Hello World! This is Test";
String slug = s.toLowerCase().replaceAll("[^a-z0-9]+", "-").replaceAll("^-+|-+$", "");
System.out.println(slug);
}
}
fun main() {
val s = "Hello World! This is Test"
val slug = s.lowercase()
.replace(Regex("[^a-z0-9]+"), "-")
.trim('-')
println(slug)
}
import Foundation
let s = "Hello World! This is Test"
let slug = s.lowercased()
.replacingOccurrences(of: "[^a-z0-9]+", with: "-", options: .regularExpression)
.trimmingCharacters(in: CharacterSet(charactersIn: "-"))
print(slug)
void main() {
final s = "Hello World! This is Test";
final slug = s
.toLowerCase()
.replaceAll(RegExp(r'[^a-z0-9]+'), '-')
.replaceAll(RegExp(r'^-+|-+$'), '');
print(slug);
}
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s = "Hello World! This is Test";
string slug;
bool prevHyphen = false;
for (char c : s) {
if (isalnum((unsigned char) c)) {
slug += tolower(c);
prevHyphen = false;
} else if (!prevHyphen && !slug.empty()) {
slug += '-';
prevHyphen = true;
}
}
while (!slug.empty() && slug.back() == '-') slug.pop_back();
cout << slug << endl;
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main() {
char s[] = "Hello World! This is Test";
char slug[100];
int idx = 0, prevHyphen = 0;
for (int i = 0; s[i]; i++) {
if (isalnum((unsigned char) s[i])) {
slug[idx++] = tolower(s[i]);
prevHyphen = 0;
} else if (!prevHyphen && idx > 0) {
slug[idx++] = '-';
prevHyphen = 1;
}
}
while (idx > 0 && slug[idx - 1] == '-') idx--;
slug[idx] = '\0';
printf("%s\n", slug);
return 0;
}