Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tyteen4a03
Last active November 13, 2022 14:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tyteen4a03/3420a9e121d13b091343 to your computer and use it in GitHub Desktop.
Save tyteen4a03/3420a9e121d13b091343 to your computer and use it in GitHub Desktop.
Shopify handleize function in JavaScript
// 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
};
@cormickjbrowne
Copy link

I'm pretty terrible with regex, but I am using this function and I had to change line 12 to this:

str = str.replace(/\W+/g, "-");

@dlindenkreuz
Copy link

@tyteen4a03
Copy link
Author

@cormickjbrowne , I'm only a year and a half late but yes, the g modifier needs to be there.

Updated!

@rm127
Copy link

rm127 commented Jul 23, 2018

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');

@pablogiralt
Copy link

@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

@pablogiralt
Copy link

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