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 ofmatch(/[aeiou]/gi)
. – ndnenkov Commented Dec 19, 2015 at 22:54
2 Answers
Reset to default 5This 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)
};