Regex are a powerful tool when it comes to string manipulation. For instance this expression /\s+/g
in combination with .replace()
method works well. To note: the /g
stands for globally. I find it very useful when working with urls.
let string = "ciao come stai oggi ?"
string.replace(/\s+/g, "-")
output will be: ciao-come-stai-oggi-?
For more advanced solutions, the following function converts a string into a slug:
// Slugify a string
function slugify(str)
{
str = str.replace(/^\s+|\s+$/g, '');
// Make the string lowercase
str = str.toLowerCase();
// Remove accents, swap ñ for n, etc
var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđßÆa·/_,:;";
var to = "AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
// Remove invalid chars
str = str.replace(/[^a-z0-9 -]/g, '')
// Collapse whitespace and replace by -
.replace(/\s+/g, '-')
// Collapse dashes
.replace(/-+/g, '-');
return str.substring(1,40);
}