AngularJS - How to Create a Custom Slugify Filter for SEO friendly URL

AngularJS - How to Create a Custom Slugify Filter for SEO friendly URL

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

  1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head>
  4. <title>AngularJS - Custom Filter for converting each character into lower case</title>
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  6. <script type="text/javascript">
  7. var myApp=angular.module('myApp',[]);
  8. myApp.filter('toLowerCase', function () {
  9. return function (input) {
  10. if (!input)
  11. return;
  12. // make lower case
  13. var slug = input.toLowerCase();
  14. return slug;
  15. };
  16. });
  17. </script>
  18. </head>
  19. <body>
  20. <h3>Custom Filter for converting each character into lower case</h3>
  21. <input type="text" ng-model="slug">
  22. <br>
  23. {{slug | toLowerCase}}
  24. </body>
  25. </html>
Create a Custom Slugify Filter for SEO friendly URL

  1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head>
  4. <title>AngularJS - How to Create a Custom Slugify Filter for SEO friendly URL</title>
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  6. <script type="text/javascript">
  7. var myApp=angular.module('myApp',[]);
  8. myApp.filter('slugify', function () {
  9. return function (input) {
  10. if (!input)
  11. return;
  12. // make lower case and trim
  13. var slug = input.toLowerCase().trim();
  14. // replace invalid chars with spaces
  15. slug = slug.replace(/[^a-z0-9\s-]/g, '');
  16. // replace multiple spaces or hyphens with a single hyphen
  17. slug = slug.replace(/[\s-]+/g, '-');
  18. return slug;
  19. };
  20. });
  21. </script>
  22. </head>
  23. <body>
  24. <h3>Custom Slugify Filter for SEO friendly URL</h3>
  25. <input type="text" ng-model="slug">
  26. <br>
  27. {{slug | slugify}}
  28. </body>
  29. </html>

Phone: (+91) 8800417876
Noida, 201301