最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Create a stringToSlug() prototype function in javascript - Stack Overflow

programmeradmin1浏览0评论

I have used the answers here as an examples although I would prefer to write it like this: value.stringToSlug()

So I have changed it to this:

// String to slug
String.prototype.stringToSlug = function(str) {
      str = str.replace(/^\s+|\s+$/g, ''); // trim
      str = str.toLowerCase();
      str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
               .replace(/\s+/g, '-') // collapse whitespace and replace by -
               .replace(/-+/g, '-'); // collapse dashes
      return str;
};

It works if I pass the string like this:

var value = $(this).val();
value.stringToSlug(value);

I have used the answers here as an examples although I would prefer to write it like this: value.stringToSlug()

So I have changed it to this:

// String to slug
String.prototype.stringToSlug = function(str) {
      str = str.replace(/^\s+|\s+$/g, ''); // trim
      str = str.toLowerCase();
      str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
               .replace(/\s+/g, '-') // collapse whitespace and replace by -
               .replace(/-+/g, '-'); // collapse dashes
      return str;
};

It works if I pass the string like this:

var value = $(this).val();
value.stringToSlug(value);
Share Improve this question edited May 23, 2017 at 12:07 CommunityBot 11 silver badge asked Oct 12, 2012 at 14:28 John MagnoliaJohn Magnolia 16.8k39 gold badges169 silver badges274 bronze badges 1
  • Is there another way to get the value of the string without passing it as a param? – John Magnolia Commented Oct 12, 2012 at 14:30
Add a ment  | 

1 Answer 1

Reset to default 13

If you're modifying any prototype you can take advantage of the fact that this refers to the object itself; in this case it points to the string you're calling the method on:

String.prototype.stringToSlug = function() { // <-- removed the argument
    var str = this; // <-- added this statement

      str = str.replace(/^\s+|\s+$/g, ''); // trim
      str = str.toLowerCase();
      str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
               .replace(/\s+/g, '-') // collapse whitespace and replace by -
               .replace(/-+/g, '-'); // collapse dashes
      return str;
};

Then call like this:

$(this).val().stringToSlug();
发布评论

评论列表(0)

  1. 暂无评论