Home > Software engineering >  Javascript - Regex for allowing only selected special characters only
Javascript - Regex for allowing only selected special characters only

Time:12-09

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

I have tried the below :

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

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

Eg :

var sampleText: string = "TestSample&123"

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

CodePudding user response:

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

CodePudding user response:

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 = /^[?*=.@#$%!^":,:;<'> -_]*$/

CodePudding user response:

You can try to use the below regex:

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

  • Related