0

Here is my source code. I have written a directive in angularjs to eliminate spaces. It's perfectly working for spaces between words but is still allowing spaces at the beginning.

function customValidation() {

   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {

       modelCtrl.$parsers.push(function (inputValue) {

         var transformedInput = inputValue.toLowerCase().replace(/ /g,''); 

         if (transformedInput!== inputValue) {
           modelCtrl.$setViewValue(transformedInput);
           modelCtrl.$render();
         }         

         return transformedInput;         
       });
     }
   };
}
deltree
  • 3,756
  • 1
  • 30
  • 51

1 Answers1

1

If you want to remove whitespace just from the beginning

inputValue.toLowerCase().replace(/^\s+/, '').replace(/\s+/g, ' '); 
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Hi martin, thank you,your example is working for me but my case it should not allow spaces on the beggining and it should allow only one space after a word. but the regular expressiion you have given is accepting more white space after a word. If you have any ideas to eliminate more spaces after a word please share thanks... – Varathan Swaminath Jul 08 '16 at 15:08
  • In the context of the current approach, `/g` is totally meaningless here. How many starts of the string can there be in a string? Yes, 1. – Wiktor Stribiżew Jul 08 '16 at 15:12
  • @VarathanSwaminath - sure, updated to remove multiple spaces between words. Wiktor - good point! – Martin Konecny Jul 08 '16 at 15:18
  • @martin thanks a lot it worked... :) – Varathan Swaminath Jul 08 '16 at 15:46