Home > OS >  String should not contain two consecutive forward slashes and any of the special character except un
String should not contain two consecutive forward slashes and any of the special character except un

Time:12-16

Looking for a JS regex which should return false, when the string contains :

  1. Two consecutive forward slash, Or/And
  2. Any of the special character except hyphen and underscore.

Note: It should have cross browser compatibility as negative lookahead/lookbehind is not supported in Safari.

I have tried this regex: /(^[\w-\/] $)(?<!.*?\/{2,}.*$)/ It works for my use case but its not supported in safari, because of the negative lookbehind.

Expected Behaviour :

Can Match any below:

asc/_bsj
acs-h-
acs
acs/bgt

Can't match any below:

acs//
acs/@
acs@

CodePudding user response:

const regex = /\/\/|[!.*?@]/g
const strings = [
'asc/_bsj',
'acs-h-',
'acs',
'acs/bgt',
'acs//',
'acs/@',
'acs@'
]

for (const string of strings) {
  console.log(string, string.match(regex) ? 'no' : 'yes')
}

CodePudding user response:

You could write your pattern without any lookarounds by removing the / from the character class, and optionally repeat the allowed characters with a leading forward slash.

^[\w-] (?:\/[\w-] )*$

Regex demo

const regex = /^[\w-] (?:\/[\w-] )*$/;
[
  "asc/_bsj",
  "acs-h-",
  "acs",
  "acs/bgt",
  "acs//",
  "acs/@",
  "acs@"
].forEach(s =>
  console.log(`${s} --> ${regex.test(s)}`)
);

  • Related