Main problem:
Remove accents and symbols slugify, but leaving dash at the end.
Before we go to the main problem, there are several parts of you code that needs mending.
- The first
replace()
statement, works for dashes that between any other strings, but would definitely be a problem if dashes are placed in both ends of a string.
e.g. '-Some-Text-'
results to 'undefinedSome-Textundefined'
To solve this problem you need to add the second argument for replace()
with an empty string.
From:
str = slug.replace("-");
To:
str = slug.replace('-', '');
- The second
replace()
statement has a regular expression flag representing, i
, representing for a case-insensitive search. While your regular expression statement suggests an A-Z
(uppercase expression), this in fact is redundant, since you've already modified the string into a lower case. So the statement should be changed:
From:
str = str.replace(/[^A-Z0-9]+/ig, "-");
To:
str = str.replace(/[^a-z0-9]+/g, "-");
- Now for the main problem, you're simply missing a dash trimming function for both ends of the string.
Add this replace statement after the code in #2
str = str.replace(/^-+|-+$/g, '');
From what I see in your code, this seems to be more of a reusable function rather than something that can be attributed to a controller function. You can create a service for this specific function instead and inject it in your controller.
DEMO
.controller('SluggerController', function($scope, slugify) {
$scope.slug = 'Neymar the best player!';
$scope.item = { slug: '' };
$scope.slugify = function(slug) {
$scope.item.slug = slugify(slug);
};
})
.factory('slugify', function() {
return function(text) {
return angular.lowercase(text)
.replace('-', '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
};
});
UPDATE:
Since you don't want to include unicode characters as dashed characters then you can incorporate this with #2.
DEMO
Instead of:
str = str.replace(/[^a-z0-9]+/g, "-");
Change it to:
str = str.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w0-9]/g, '-');
As for how I got the regular expression, you can refer to this SO comment