Javascript Regular Expressions Use variables

Source: Internet
Author: User


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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.