Hi Friends 👋,
Welcome To Infinitbility! ❤️
To remove special characters from string in react js, just use replace()
method with /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g
regex then it will return new string without special characters.
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Let’s take an example to remove special characters using replace()
method.
const regex = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;
var str = "(in)[fi]ni`tb*il#it%y";
str.replace(regex, '');
// 👇️ Output
// "infinitbility"
Today, I’m going to show you How do I remove special characters from string in react js, as above mentioned here, I’m going to use the replace()
method with /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g
regex to delete special characters from string.
Let’s start today’s tutorial how do you remove special characters from string in react js?
In this example, we will do
- create sample string state
- used
replace()
method with regex to remove special characters - print the output string in the screen
Let’s write code…
react js substring example
import React, { useState, useEffect } from "react";
export default function App() {
const regex = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/g;
const [str, setStr] = useState("(in)[fi]ni`tb*il#it%y");
return (
<div className="App">
<p>{str.replace(regex, '')}</p>
</div>
);
}
As mentioned above, we are taken the example of a string state, remove special characters from string and print the output in the screen.
I hope it’s help you, All the best 👍.