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
1 Answer
Reset to default 13If 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();