Last active
November 13, 2022 14:35
-
-
Save tyteen4a03/3420a9e121d13b091343 to your computer and use it in GitHub Desktop.
Shopify handleize function in JavaScript
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
// from https://github.com/Shopify/liquid/blob/63eb1aac69a31d97e343822b973b3a51941c8ac2/performance/shopify/shop_filter.rb#L100 | |
Shopify.handleize = function (str) { | |
str = str.toLowerCase(); | |
var toReplace = ['"', "'", "\\", "(", ")", "[", "]"]; | |
// For the old browsers | |
for (var i = 0; i < toReplace.length; ++i) { | |
str = str.replace(toReplace[i], ""); | |
} | |
str = str.replace(/\W+/g, "-"); | |
if (str.charAt(str.length - 1) == "-") { | |
str = str.replace(/-+\z/, ""); | |
} | |
if (str.charAt(0) == "-") { | |
str = str.replace(/\A-+/, ""); | |
} | |
return str | |
}; |
@rm127 I think you can use normalize function (remove accents and similar) like this:
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
or like this:
str.normalize("NFD").replace(/\p{Diacritic}/gu, "")
sources here:
https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
and here
https://ricardometring.com/javascript-replace-special-characters
Here a versión of this with normalization of accents and other language especial characters:
https://gist.github.com/pablogiralt/f52d27428e7501909616d1dea04edfeb
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two years late here, but support for scandinavian characters such as "æ", "ø" and "å" is missing. Also other language-specific letters aren't converted to ther plain value fx: é -> e etc.
Fix for the first problem:
str = str.replace('ø','o').replace('æ','ae').replace('å','a');