React js Bold Specfic Text In a String
React js Bold Specfic Text In a String :To bold specific text in a string using React.js, you can create a function that takes the original string and the target keyword as arguments. Inside the function, use JavaScript's replace
method with a regular expression to find and wrap the keyword in HTML <strong>
tags. Then, render the string within your React component, either by using dangerouslySetInnerHTML
to allow HTML rendering (with caution for security) or by applying CSS styles to the wrapped text. This approach enables you to dynamically highlight specific text within strings, enhancing text presentation and user experience in React.js applications.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
React js Bold Specfic Text In a String Example
Copied to Clipboard
xxxxxxxxxx
<script type="text/babel">
const makeBold = (item, keywords) => {
let result = item;
keywords.forEach(keyword => {
const re = new RegExp(keyword, 'g');
result = result.replace(re, `<span>${keyword}</span>`);
});
return result;
};
function App() {
const items = ['Font Awesome Icons', 'Sarkari Naukri Exams', 'Tutorials Plane'];
const boldKeywords = ['Awesome', 'Naukri'];
return (
<div className="container text-bold">
<h3>React Js Bold Specfic Text In A String</h3>
<ul>
{items.map((item, index) => (
<li key={index} dangerouslySetInnerHTML={{ __html: makeBold(item, boldKeywords) }}
/>
))}
</ul>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of React js Bold Specfic Text In a String
Ad