问题描述
我正在尝试实现动态ngPattern.
I'm trying to implement dynamic ngPattern.
当用户单击按钮或从下拉列表中选择一个值时,我的正则表达式会更改.
My regex changes when the user clicks on a button or selects a value from dropdown.
但是由于某种原因,这似乎不起作用.下面是代码.
But for some reason this doesnt seem to work. Below is the code.
app.controller('testController',function(){
$scope.pattern = new RegExp('^\w{1,10}$');
$scope.changePattern = function () {
$scope.pattern = new RegExp('^\d{5}$');
};
});
但是当我尝试类似的方法时,它会起作用.
But when i try something like this, it works.
$scope.pattern = /^\w{1,10}$/;
$scope.changePattern = function () {
$scope.pattern = /^\d{5}$/;
};
我不确定为什么不能使用新的RegExp().我必须使用新的RegExp()的原因是,我在JSON响应中将它作为字符串获取了.
I'm not sure why using new RegExp() is not working. The reason I had to use new RegExp() is that I get this in a JSON response as string.
推荐答案
这是因为反斜线(\
)是一个特殊字符,在构造字符串时需要使用"\\"
进行转义:
This is because backlash (\
) is a special character that you need to escape with "\\"
when you are constructing a string:
$scope.pattern = new RegExp('^\\w{1,10}$');
因此,这与RegExp
或ng-pattern
无关.
这篇关于角动态ngPattern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!