Last active
September 16, 2021 11:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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