sTg
sTg

Reputation: 4424

Javascript - Regex for allowing only selected special characters only

I want to allow only specific special characters like in a text like ?*=.@#$%!^":,:;<'>+-_.

I have tried the below code:

pattern = new RegExp(/^(?=.*?[?*=.@#$%!^":,:;<'>+-_])/);

It does not seem to work, it seems to pass even if I am entering a special character other than the ones specified above. Am I missing something here?

e.g.:

var sampleText: string = "TestSample&123"

The above example should throw an error and fail since I have not used any of the special character which is specified in the pattern.

Upvotes: 0

Views: 953

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

You can try to use the below regex:

    const str = /^[a-zA-Z0-9?*=.@#$%!^":,:;<'>+-_]+$/;
    
    console.log(str.test('TestSample&123')); 

Upvotes: 0

Dylan
Dylan

Reputation: 13922

A few things:

  • Javascript has regex literals, so you can do var regex = /^(?=.*?[?*=.@#$%!^":,:;<'>+-_])/ instead of new Regex(...)
  • https://regex101.com/ is a super helpful resource for figuring out regex. Paste ^(?=.*?[?*=.@#$%!^":,:;<'>+-_]) into that site and it'll explain what each part does.
  • The ^ at the beginning of the regex anchors the matching to the beginning of the string, but you don't have a corresponding $ to make sure the match applies to the entire string.
  • The (?=.*? is a positive lookahead that mathces any number of any character. The character group [...] that you have is only going to match a single character, when it sounds like you want it to match all of the characters.

Rahul already answered while I was typing this up, and he's got the right expression:

^[?*=.@#$%!^":,:;<'>+-_]*$

The ^ anchors the match to the beginning of the string, and the $ anchors the end of the match to the end of the string. The [...]* will match any number of characters as long as they belong to that set of characters.

You can make a JS var out this like

var myRegex = /^[?*=.@#$%!^":,:;<'>+-_]*$/

Upvotes: 1

Alexander Nied
Alexander Nied

Reputation: 13623

Based on the charset you want and the approach from this answer here about exclusive sets in Regex, you should be able to do something like this:

const testPattern = /^[?*=.@#$%!^":,;<'>+\-_]+$/;

console.log(testPattern.test('?*+@!')); // passes
console.log(testPattern.test('TestSample&123')); // fails

Upvotes: 1

Related Questions