简体   繁体   中英

How to assign regex to variable for later use on a string?

I currently have this:

var input = "some input";
var firstRegex = input.match(/[aeiou]/gi);
var secondRegex = /ee/.test(input);

So if the input variable is undefined, both regex's will stop the code from compiling in the browser.

Is there a way to assign the regex's to variables so that they can later be called on input?

For example, inside an object:

var checkStrings = {

 firstRegex : match(/[aeiou]/gi),
 secondRegex : /ee/,

}

// call on input
 checkStrings.firstRegex(input);

This link from Mozilla goes into a little more detail about the RegExp object in js, but if you want to simply assign a regexp to a variable, you can just do:

var firstRegex = new RegExp(/[aeiou]/gi);
var secondRegex = new RegExp(/ee/);

Then you would call them the same way you do now.

if (input) {
    var matches = input.match(firstRegex);
    var passedTest = secondRegex.test(input);
}

You could obviously do this much easier in an object as @IIya suggested, but I thought I'd add some info about the RegExp object in js.

You can use predicates:

var checkStrings = {
    checkFirstRegex = function(x) { 
        return x.match(/[aeiou]/gi);
    },
    checkSecondRegex = function(x) {
        return /ee/.test(x);
    }
};

// call on input
checkStrings.firstRegex(input);

With the ES6 arrow functions it becomes even shorter:

var checkStrings = {
    checkFirstRegex = x=> x.match(/[aeiou]/gi),
    checkSecondRegex = x => /ee/.test(x)
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM