Home > database >  JS: adding multiples rules within replace method?
JS: adding multiples rules within replace method?

Time:11-16

I was using the replace method with the following regex to strip periods at the end of a string: replace(/\.[^/.] $/, ""); . Now I want to change this to meet the following requirements:

  • can't end with a period,
  • can't contain only spaces
  • can't contain the following characters: \ / * ? " | : < >

Is there a way to incorporate the other 2 rules with my rule that is already stripping the period?

CodePudding user response:

s = s
   .replaceAll(/\s/g, '')
   .replaceAll(/[\\/*?"|:<>]/g, '')
   .replace(/\. $/, '')

CodePudding user response:

Use this combined regex, which will match all of the things you would like to exclude: /\. $|\\|\/|\*|\?|\"|\||\:|\<|\>|^\s $/g.

To remove invalid characters from a string, use:

s = s.replace(/\. $|\\|\/|\*|\?|\"|\||\:|\<|\>|^\s $/g, '')
if (!s) {
  // The string is entirely whitespace
}

If you just want to check the existence of invalid characters, use:

if (/\. $|\\|\/|\*|\?|\"|\||\:|\<|\>|^\s $/g.exec(s)) {
  // The string is invalid
} else {
  // The string is valid
}
  • Related