Solution

To check string contains special characters in react js, use the this regex /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/ with test() method it will return true if string got in special char.

Snippet

In this snippet section, we will see an example of checking string contains special characters or not in react.

const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
const str = "ReactJs@Snippet";

console.log(specialChars.test(str)) // true

Example

In this example, we will check string contain special characters or not and print in console and page.

Let’s start coding…

App.js

import { useState, useEffect } from "react";
const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
export default function App() {
  const [str, setStr] = useState("ReactJs@Snippet");

  useEffect(() => {
    console.log(specialChars.test(str));
  }, []);

  return (
    <div>
      <p>{specialChars.test(str).toString()}</p>
    </div>
  );
}

Output

test, special, char

codesandbox