In this article, you will look at an example of how to replace a string in React using the replace()
method.
How To Replace String In React Apps
Here, you will learn step by step on how to replace in react js app using JS Replace() Method.
- Step 1 – Create React App
- Step 2 – Install React Bootstrap
- Step 3 – Create String Component
- Step 4 – Import String Component in App.js
Step 1 – Create React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install React Bootstrap
In this step, execute the following command to install react boostrap library into your react app:
npm install bootstrap --save
Add bootstrap.min.css file in src/App.js
file:
import React, { Component } from 'react'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>How To string replace in React js</h2>
</div>
);
}
export default App;
Step 3 – Create String Component
In this step, create StringReplaceComponent.js file in src
directory of your react js app, and create string component file named StringReplaceComponent.js in it:
import React from 'react'
class StringReplaceComponent extends React.Component{
render(){
var myStr = "Hi Developers!";
var newStr = myStr.replace("Hi", "Welcome");
return(
<div>
<h1>String Replace Example</h1>
<p><strong>Old String : </strong>{myStr}</p>
<p><strong>New String : </strong>{newStr}</p>
</div>
);
}
}
export default StringReplaceComponent;
Step 4 – Import String Component in App.js
In this step, you need to add StringReplaceComponent.js file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import StringReplaceComponent from './StringReplaceComponent'
function App() {
return (
<div className="App">
<StringReplaceComponent />
</div>
);
}
export default App;
Conclusion
String replace in react js example; In this tutorial, you have learned how to replace string react js apps.