This article introduces some problems and solutions when using variables in Javascript Regular Expressions. It mainly describes the replacement and RegExp methods.
Example 1: replace with a variable
The replace function can be replaced by a regular expression that matches strings.
The problem we encountered today is that the regular expression has a variable. Take the actual situation today as an example:
| The Code is as follows: |
Copy code |
|
/(^ '+ Arr2 [I] +' |) | (| '+ arr2 [I] +' $ )/
Arr2 [I] is an array element and a variable.
Str = str. replace (/(^ '+ arr2 [I] +' |) | (| '+ arr2 [I] +' $ )/,''); |
This method cannot be replaced successfully. solution:
| The Code is as follows: |
Copy code |
|
Var reg = eval_r ('/(^' + arr2 [I] + '\ |) | (\ |' + arr2 [I] + '$ )/');
Str = str. replace (reg ,''); |
If it is a direct variable, we can replace it as follows:
| The Code is as follows: |
Copy code |
|
Var match_str = 'bitch ';
Var regex = "/," + match_str + ",/ig ";
Var target_str = ", abcde, bitch, fghij ,";
Var val = target_str.replace (eval (regex ),",");
Alert (val ); |
Val should be:, abcde, fghij,
Example 2: RegExp mode with variables
| The Code is as follows: |
Copy code |
|
Function checkBeginWithChar (str, minlen, maxlen, msg)
{
Minlen = minlen-1;
Maxlen = maxlen-1;
Var re = new RegExp ("^ [a-zA-Z] {1} ([a-zA-Z0-9]) {" + minlen + "," + maxlen + "} $ ");
If (! Re.exe c (str )){
Alert (msg );
Return false ;}
Return true;
} |
The above is a JavaScript function, which can be called as follows:
| The Code is as follows: |
Copy code |
|
If (! CheckBeginWithChar ("a123df", 6,12, "Your entered PIN must start with a letter and contain between 6 and 12 characters !"))
Return false; |
This is where variables are used. The following function does not use variables.
| The Code is as follows: |
Copy code |
|
Function checkBeginWithChar (str, msg)
{
Var patrn =/^ [a-zA-Z] {1} ([a-zA-Z0-9]) {5, 50} $ /;
If (! Patrn.exe c (str )){
Alert (msg );
Return false;
}
Return true;
} |
Note: When no variable is available, the regular expression can have a backslash on both sides without being written as a string. If the variable is used, use new RegExp () and the strings in them do not have the two backslash.