create a reg ex accepting only alphabetical characters, special characters and spaces in javascript

Here's a regex pattern you can use to accept only alphabetical characters (both lowercase and uppercase), special characters, and spaces in JavaScript:

index.tsx
/^[a-zA-Z\s\W]+$/
18 chars
2 lines

Breakdown of the pattern:

  • ^: beginning of the string
  • [a-zA-Z]: matches any alphabetical character (both lowercase and uppercase)
  • \s: matches any whitespace character (space, tab, newline)
  • \W: matches any non-word character (special character)
  • +: one or more of the above characters
  • $: end of the string

Here's an example usage in JavaScript:

index.tsx
const regex = /^[a-zA-Z\s\W]+$/;
const input = "Hello, World!"; // example input
const isValid = regex.test(input);

console.log(isValid); // true
147 chars
6 lines

gistlibby LogSnag