sagar
sagar

Reputation: 1432

using regex set in javascript object property

I have to use regular expression which is set in javascript's object property, like below

var myObj = { mask : /([a-z]|[A-Z]|[0-9]|-|\.|\'|[&])/}

in some other function which will get myObj as parameter and in that function I need to test that if string contains any character not matching above regex. Example

function check(myObj , value){
//Want to code here to read myObj.mask and return false if value contains 
//any character not matching myObj.mask. as per above example if value contain any special character 
// like &#$% then i want to return false

}

Upvotes: 3

Views: 1443

Answers (2)

acdcjunior
acdcjunior

Reputation: 135802

Your regex is very redundant, you are doing lots of unnecessary escaping. You can use the shorter version:

/^([a-zA-Z0-9-.'&])*$/

Notice I added some anchors, they are necessary for RegExp.test();

var myObj = { mask : /^([a-zA-Z0-9-.'&])*$/ }

function check(myObj , value){
    return myObj.mask.test(value);
}

console.log(check(myObj, "abc1-.'&")); //true
console.log(check(myObj, "&#$%")); //false
console.log(check(myObj, "abc#")); //false

Explanation for /^([a-zA-Z0-9-.'&])*$/

  • ^ the beginning of the string
  • ( group and capture start group 1
  • [a-zA-Z0-9-.'&] any character of: a to z, A to Z, 0 to 9, -, ., ' or &
  • ) end of group 1
  • * group 1 zero or more times
  • $ end of the string

It is simpler than the original because [a-z]|[A-Z] is the same as [a-zA-Z]. Also, inside character classes (that is, between [ and ]), you don't have to escape ., ' or &.

If you can't change the expression

In that case, we can create a new RegExp object, adapting the one passed as parameter.

var myObj = { mask : /([a-z]|[A-Z]|[0-9]|-|\.|\'|[&])/ }

function check(myObj , value){
    return new RegExp('^'+myObj.mask.source+'*$').test(value);
}

console.log(check(myObj, "abc1-.'&")); // true
console.log(check(myObj, "&#$%")); // false
console.log(check(myObj, "abc#")); // false

Upvotes: 2

SoWhat
SoWhat

Reputation: 5622

This can be done by

return myObj.mask.test(value)

Upvotes: 0

Related Questions