最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to assign regex to variable for later use on a string? - Stack Overflow

programmeradmin1浏览0评论

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 piling 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);

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 piling 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);
Share Improve this question asked Dec 19, 2015 at 22:52 user3737841user3737841 6652 gold badges8 silver badges10 bronze badges 1
  • 1 What about just /[aeiou]/gi instead of match(/[aeiou]/gi). – ndnenkov Commented Dec 19, 2015 at 22:54
Add a ment  | 

2 Answers 2

Reset to default 5

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 bees even shorter:

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

评论列表(0)

  1. 暂无评论