Example 1,replace with variable
The Replace function can use regular expressions to match string implementation substitutions.
The problem encountered today is that the regular expression has a variable, taking today's actual situation as an example:
| The code is as follows |
Copy Code |
/(^ ' +arr2[i]+ ' |) | (|' +arr2[i]+ ' $)/ Arr2[i] is an array element and is a variable Str=str.replace (/^ ' +arr2[i]+ ' |) | (|' +arr2[i]+ ' $)/, '); |
You cannot replace success with this approach:
| 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 with the following actions
| 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 variable
| 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.exec (str)) { Alert (msg); return false; } return true; } |
The above is a JavaScript function that can be invoked like this:
| The code is as follows |
Copy Code |
If (!checkbeginwithchar ("A123DF", 6, 12, "The pin you enter must begin with a letter and the number of characters is between 6-12!") ”))
return false; |
This is a case of using a variable, and the following function is not using a variable.
| 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.exec (str)) { Alert (msg); return false; } return true; } |
Note: When there is no variable, the regular expression can have a backslash on both sides, not as a string, if you use a variable with the new RegExp () and the inside string has no two backslashes.