Search code examples
javascriptregexangularjsng-pattern

Different ng-pattern Behaviors


Scenario

I'm using ng-pattern in a project where I need to dynamically generate regular expressions via string concatenation meaning the end result is var regexp = "regexp" rather than var regexp = /regexp/.

The Problem

I know that this code works:

//JavaScript
$scope.regex = /[^0-9\|]+/;

//HTML
<input type="text" name="first" ng-model="a" ng-pattern="regex">

But I need to be able to use a string like so:

//JavaScript
$scope.regex = "[^0-9\|]+";

//HTML
<input type="text" name="first" ng-model="a" ng-pattern="{{regex}}">

The Question

How can I use my dynamically generated string regular expression with ng-pattern?

Plunker

I've prepped a plunker demonstrating three different uses of ng-pattern in which only the literal regular expression works. I'd be so grateful for any help. Thanks!


Solution

  • When you do var c = /string/; You're creating a regex literal. This is not the only way to create a regex in JS. Like you can create objects by other means than object literals. RegExp takes in a string and returns a regex literal using that string as the pattern.

    $scope.regex = new RegExp(string)
    

    So if I wanted to create a regex dynamically using concated strings. It would look like something like this.

    var something = "a";
    something += "|b"
    $scope.regex = new RegExp(something);
    // $scope.regex == /a|b/