Skip to content

Instantly share code, notes, and snippets.

@pablogiralt
Last active February 6, 2024 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablogiralt/f52d27428e7501909616d1dea04edfeb to your computer and use it in GitHub Desktop.
Save pablogiralt/f52d27428e7501909616d1dea04edfeb to your computer and use it in GitHub Desktop.
Shopify handlelize function in javascript
// handlelize in liquid: https://github.com/Shopify/liquid/blob/63eb1aac69a31d97e343822b973b3a51941c8ac2/performance/shopify/shop_filter.rb#L100
// how to handlelize in js: https://ricardometring.com/javascript-replace-special-characters
function handlelize (str) {
str = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '') // Remove accents
.replace(/([^\w]+|\s+)/g, '-') // Replace space and other characters by hyphen
.replace(/\-\-+/g, '-') // Replaces multiple hyphens by one hyphen
.replace(/(^-+|-+$)/g, '') // Remove extra hyphens from beginning or end of the string
.toLowerCase(); // To lowercase
return str
};
export default handlelize;
@jonXmack
Copy link

jonXmack commented Feb 6, 2024

@pablogiralt based on the liquid handleize I have adjusted it to the following

// handlelize in liquid: https://github.com/Shopify/liquid/blob/63eb1aac69a31d97e343822b973b3a51941c8ac2/performance/shopify/shop_filter.rb#L100
// how to handlelize in js: https://ricardometring.com/javascript-replace-special-characters

function handlelize(str) {
  str = str
    .normalize('NFD')
    .replace(/[\[\]'()"]+/g, '') // Remove apostrophes, square brackets, and other bits and pieces
    .replace(/[\u0300-\u036f]/g, '') // Remove accents
    .replace(/([^\w]+|\s+)/g, '-') // Replace space and other characters by hyphen
    .replace(/\-\-+/g, '-') // Replaces multiple hyphens by one hyphen
    .replace(/(^-+|-+$)/g, '') // Remove extra hyphens from beginning or end of the string
    .toLowerCase(); // To lowercase

  return str;
}

export default handlelize;

The only addition is line 7 to reflect https://github.com/Shopify/liquid/blob/main/performance/shopify/shop_filter.rb#L100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment