1

I would like to know regex code to check whether it contains Special characters other than hypen and forwardslash in javascript

function containsSpecialCharacters(str){
    var regex = /[~`!#$%\^&*+=\-\[\]\';,/{}|\\":<>\?]/g;
        return regex.test(str);
  }


var result = containsSpecialCharacters("sample"); // false
var result = containsSpecialCharacters("sample-test"); // false
var result = containsSpecialCharacters("sample++"); // true
var result = containsSpecialCharacters("/sample/test"); // false
miyavv
  • 763
  • 3
  • 12
  • 30

3 Answers3

0

You can use a normal regex to search for all ASCII special characters, like this one, and then just remove the hypen and backslash:

/[!$%^&*()_+|~=`{}\[\]:";'<>?,.]/

If you want to avoid any other special character, you just have to remove it from the regex.

You can test this regex here: https://regex101.com/r/gxYiGp/2

Heisenbug
  • 213
  • 1
  • 6
0

If you need to support only English characters, it would be far easier to list the exceptions than those you wish to match:

/[^\w\s\\\-]/.test(myString);

As noted, though, this will fail if you need to support international characters.

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

you can just negate it so it looks shorter, like this :

[^\s\w-]
NMI
  • 509
  • 5
  • 8