如果您想替换除
\w
,
_
和
[^\w_ ]
(当然逃走了)。
用下面的代码替换代码中的regex:
new RegExp('[^\\w_ ]', 'gi')
注意
\s
:
这个
\s公司
)但它也匹配其他类型的空白空间(
\r\n\t\f\v
检查下面的工作代码。
angular.module('app', [])
.controller('myCtrl', function($scope) {
$scope.username = '';
})
.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue === undefined)
return ''
regReplace = new RegExp('[^\\w_ ]', 'gi');
if (inputValue === undefined)
return ''
cleanInputValue = inputValue.replace(regReplace, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Username : <input type="text" no-special-char ng-model="username" name="userName">
</div>