In this tutorial, I will tell you how to generate SEO friendly URL by creating custom slugify filter in AngularJS.
There are some built in filters in angularjs that cover many common use cases such as formatting dates, search etc.
You can create custom filter by using app.filter
method by passing custom filter name. Filters are only function which gets input and apply some logics over input then return an output - transform input to an output.
In this example, I will create custom filter that can be used for converting a string into sluggable URL.
First, I will show you how to create simple custom filter for converting each character into lower case.
Simple custom filter for converting each character into lower case
- <!DOCTYPE html>
- <html ng-app="myApp">
- <head>
- <title>AngularJS - Custom Filter for converting each character into lower case</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
- <script type="text/javascript">
- var myApp=angular.module('myApp',[]);
- myApp.filter('toLowerCase', function () {
- return function (input) {
- if (!input)
- return;
- // make lower case
- var slug = input.toLowerCase();
- return slug;
- };
- });
- </script>
- </head>
- <body>
- <h3>Custom Filter for converting each character into lower case</h3>
- <input type="text" ng-model="slug">
- <br>
- {{slug | toLowerCase}}
- </body>
- </html>
- <!DOCTYPE html>
- <html ng-app="myApp">
- <head>
- <title>AngularJS - How to Create a Custom Slugify Filter for SEO friendly URL</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
- <script type="text/javascript">
- var myApp=angular.module('myApp',[]);
- myApp.filter('slugify', function () {
- return function (input) {
- if (!input)
- return;
- // make lower case and trim
- var slug = input.toLowerCase().trim();
- // replace invalid chars with spaces
- slug = slug.replace(/[^a-z0-9\s-]/g, '');
- // replace multiple spaces or hyphens with a single hyphen
- slug = slug.replace(/[\s-]+/g, '-');
- return slug;
- };
- });
- </script>
- </head>
- <body>
- <h3>Custom Slugify Filter for SEO friendly URL</h3>
- <input type="text" ng-model="slug">
- <br>
- {{slug | slugify}}
- </body>
- </html>