I found this really strange behavior when defining a regex as a class property in ES6. I currently encountered this behavior working with typescript and angular, but I made a stripped version in my chrome console and it was the same.
class RegexTest {
constructor() {
this.expression = /[\*|\-|\_]/g;
}
testStringExpression(word) {
return this.expression.test(word);
}
}
const tester = new RegexTest();
const words = "*, *, *, kitten";
const reduced = words.split(',').reduce((acc, item, index) => {
if ( tester.testStringExpression(item) ) {
return acc;
} else {
return acc + item + index;
}
}, "");
console.log(reduced); // Should be " kitten3", instead I'm getting " *2 kitten3"
However, If I just test the regular expression as it is inside the reduce, the result is the expected:
const words = "*, *, *, kitten";
const reduced = words.split(',').reduce((acc, item, index) => {
if ( /[\*|\-|\_]/g.test(item) ) {
return acc;
} else {
return acc + item + index;
}
}, "");
console.log(reduced); // " kitten3"
What am I'm getting wrong here?