In the following example I want to test if a string consists of allowed characters. However I don't get the expected result. What am I missing?
const string = 'sdf^&&*^%^';
const pattern = "\\w";
const allowed = new RegExp(pattern);
const pattern2 = "\w";
const allowed2 = new RegExp(pattern);
const pattern3 = /\w/g;
document.getElementById("app").innerHTML = `
<p>This should be false (but is true): ${allowed.test(string)}</p>
<p>This should be false (but is true): ${allowed.test(string)}</p>
<p>This should be false (works): ${string.match(pattern3)}</p>
`;
------------ edit:
Turns out the previous explanation was confusing. Maybe this clears it up.
In my code the regex pattern is passed down to a child component via a property (in React). So It's not possible to pass it through using the regex itself. So maybe the question is more:
"How to use a regex pattern from a string, to match a single word a-z, A-Z, 0-9, including the _ (underscore) character."
A test setup would be:
const allowedCharacters = 'abc_123';
const unallowedCharacters = '*&^#';
const regex = /^\w+$/;
const regexString = "/^\w+$/"; // <- hence the string
// -------
console.log('--- regex without it coming from a string');
const regexObjectWithoutString = new RegExp(regex);
console.log('Should be abc_123: ', allowedCharacters.match(regex)); // ["abc_123"]
console.log('Should be true: ', regexObjectWithoutString.test(allowedCharacters)); // true
console.log('Should be false', regexObjectWithoutString.test(unallowedCharacters)); // false
// all good until now
// -------
console.log('--- this time regex from a string');
const regexObjectByString = new RegExp(regexString);
console.log('Should be abc_123: ', allowedCharacters.match(regexString)); // null
console.log('Should be true: ', regexObjectByString.test(allowedCharacters)); // false
console.log('Should be false', regexObjectByString.test(unallowedCharacters)); // false