jQuery: 将字符串转换为 "handle" 类似于 Shopify 的 Handleize

jQuery: Convert string to "handle" similar to Shopify's Handleize

我正在尝试对字符串执行与 Shopify 的 "handleize" 相同的操作,但使用 jQuery.

https://docs.shopify.com/themes/liquid-documentation/filters/string-filters#handle

基本上我想将任何字符串转换为句柄,所以

Hello, my name is Corey.

会变成

hello-my-name-is-corey

使用 jQuery 函数。

好吧,你真的会用正则表达式和字符串替换来做到这一点,而不是 jQuery。

var name = "Hello, my name is Corey.";
name = name.toLowerCase().replace(/ /g,'-');

您还需要删除所有其他 非字母数字字符,例如不可见字符、大多数 unicode 等,因为这很可能导致类似问题。

name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, '').replace(/^-/, '');

我做了一个小的 jQuery 扩展以在您输入文本输入并输出结果时对字符串进行 slugify:

jquery.slug.js:

jQuery.fn.slug = function(options) {
    var defaults = {
        events: 'keypress keyup blur',
        targets: ['#slug', '#hidden']
    };
    var opts  = jQuery.extend(defaults, options);

    jQuery(this).on(opts.events, function(){
      var slug = $(this).val().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, '').replace(/^-/, '');

      jQuery.each(opts.targets, function(index, element) {
        $(element).val(slug);  // input or textarea
        $(element).html(slug); // other dom elements
      });
    });
};

用法:

$('input[name="some-text-input"]').slug({targets: ['#some-id', 'input[name="some-name"]']});

/* Try this one */

function handleize(text) {
    return text.toString().toLowerCase()
               .replace(/\s+/g, '-')           // Replace spaces with -
               .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
               .replace(/\-\-+/g, '-')         // Replace multiple - with single -
               .replace(/^-+/, '')             // Trim - from start of text
               .replace(/-+$/, '');            // Trim - from end of text
}

console.log(handleize("Hello, my name is Corey."));