Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a stringToSlug() prototype function in javascript

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);
like image 597
John Magnolia Avatar asked Mar 18 '26 13:03

John Magnolia


1 Answers

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();
like image 113
Ja͢ck Avatar answered Mar 21 '26 02:03

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!