July 15, 2015
Convert Strings from hyphen-notation to camel case Part 2 (AngularJS)
In my last post i demonstrated how to convert Strings from Hyphen Format to CamelCase in Java, using the popular Framework Guava from Google.
In AngularJS this can be achieved using a Regular Expression and an AngularJS Filter.
1) Create a constant function which does the replacement
Our first step is to create a Regular expression which does the conversion from a camel Case Text to Hyphen Format. For reusing purpose we are storing this as a AngularJS constant.
1 2 3 |
angular.module('common').constant('camelCaseToHyphens', function(str) { return str.replace(/([A-Z])/g, function($1) { return '-' + angular.lowercase($1); }); }); |
2) Create an AngularJS Filter Function
The second step is to register the constant as a AngularJS Filter. The constant is injected from AngularJS
1 2 3 |
angular.module('common').filter('camelCaseToHyphens', function(camelCaseToHyphens) { return camelCaseToHyphens; }); |
3) Usage in HTML
We can now use the filter in any Html element, as displayed in the next code snippet.
1 2 3 |
<span> {{'camelCase' | camelCaseToHyphens}} </span> |
The following fiddle shows all the examples from this blog post!