Skip to content

Instantly share code, notes, and snippets.

@JoseJPR
Last active September 16, 2021 11:18
Show Gist options
  • Save JoseJPR/65b973dc2a09437211115b40ea12a223 to your computer and use it in GitHub Desktop.
Save JoseJPR/65b973dc2a09437211115b40ea12a223 to your computer and use it in GitHub Desktop.
Normalize strings in order to create pretty url. If you have to generate beautiful urls from strings in which certain characters or html elements may exist, this is your tool.
/**
* Title: Normalize strings in order to create pretty url.
*
* Description: If you have to generate beautiful urls from strings
* in which certain characters or html elements may exist, this is your tool.
*/
const urlNormalize = (str) => {
const from = Array.from('ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç');
const to = Array.from('AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc');
const mapping = Object.assign(...from.map((letter, index) => ({[letter] : to[index] })));
const res = Array
.from(str)
.reduce((result, letter) => result + (mapping[letter] || letter), '')
.trim()
.replace(/[^-A-Za-z0-9]+/g, '-') // Replace white space to -
.replace(/-+/g,'-') // Remove duplicated dashs
.replace(/<[^>]*>?/gm, '') // Replace html tags to empty
.toLowerCase(); // Transform to lower case
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment