我想在输入文本字段中的有效数字之前或之前删除或修剪零。
我有一个文本字段,并限制用户只输入数字。当我输入值为“0145”时,它应显示为“145”。
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
</div>
JavaScript的:
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
答案 0 :(得分:2)
你的正则表达式有些错误。它应该是:
var transformedInput = inputValue.replace(/^0*/g, '')
这将替换字符串
开头的所有0答案 1 :(得分:2)
将正则表达式更改为:
var transformedInput = inputValue.replace(/^[^1-9]*|[^0-9]/g, '');