这是我的源代码。我在 angularjs 中编写了一条指令来消除空格。它非常适合单词之间的空格,但在开头仍然允许空格。

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;          
       }); 
     } 
   }; 
} 

请您参考如下方法:

如果您想从开头删除空格

inputValue.toLowerCase().replace(/^\s+/, '').replace(/\s+/g, ' ');  


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!