-2

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

Fiddle: https://jsfiddle.net/Spindle/cud3sLnh/

Remi
  • 2,517
  • 3
  • 26
  • 43
  • why `allowed` and `allowed2` are using same string to build regex ? – Code Maniac Sep 30 '19 at 16:04
  • 1
    Why do you think the results you've said "should be" should be? For instance, you've used `\w`, which matches any "word" character. You've said the string shouldn't match it, but it should, because the first character in it (`s`) is a word character. If you're looking for a **full** match, you need to add anchors to your expressions. More [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and [here](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). – T.J. Crowder Sep 30 '19 at 16:05
  • Voting to close as typo/non-repro/not-useful-to-others-in-future. – T.J. Crowder Sep 30 '19 at 16:05
  • Needs more [mcve]. That "codesandbox" page doesn't work at all (and contains different code: `pattern3` is missing entirely). – melpomene Sep 30 '19 at 16:08
  • @T.J.Crowder Wasn't sure how to explain it. Added a second try which is perhaps a bit clearer. – Remi Sep 30 '19 at 18:36

1 Answers1

0

Your sample string includes some "valid characters", so the /\w/ expression will always find a match. If you want a regex to validate that it ONLY contains characters matched by \w then your expression should be /^\w+$. Which starts matching at the beginning of the string, stops matching at the end, and expects 1 or many \w characters.

I recommend using a tool like https://regexr.com that provide a visualization of the regular expressions as you are trying to build them.

TedCHoward
  • 151
  • 6
  • Thanks @TeCHoward, this brought me closer to figuring out what is happening. The pattern seems to be correct now. Only thing I'm still running into is passing a string into a RegEx. – Remi Sep 30 '19 at 18:41