'How to change background color of specific character in react/typescript using regex?
I have a component that has mapped data. My task is to change the background color of specific characters. In this case, they are "Miss", "Mrs", "Ms". I know I can use regex but I keep getting an error object is possibly null.
This is the component and what I have tried.
const h2 = document.querySelector("h2")
h2.innerHTML = h2.textContent.replace(/[ms]/g, "<span class='title'>Miss</span>");
.title {
background-color: blue;
}
.map((d: any) => (
<div style={hoverStyle} className=" ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300 border-white shadow-slate-500 bg-white hover:bg-slate-200 rounded-lg container p-5">
<img className="rounded-full w-44 h-44 " src={d.picture.large} />
<h2>{d.name.title}</h2>
<h3 className="font-bold text-3xl font-serif">
{" "}
{d.name.first} {d.name.last}
</h3>
<p className=" text-md ">Gender: {d.gender}</p>
<p className=" text-md bg-blue-300 text-white ">Contact: {d.email}</p>
<p className=" text-md ">
City: {d.location.city}
</p>
</div>
))}
</div>
This is the code sandbox
https://codesandbox.io/s/sweet-mclean-nrhcdq?file=/src/App.tsx
Solution 1:[1]
I belief you can still accomplish this in the map function.. You can do a check using a ternary operator such as {d.name.title!==undefined &&d.name.title.includes('ms')?'Miss': d.name.title}
.. You can do this outside to make your html clean and readble. To change the background color you can also apply a class conditionally using the back tick character
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mundruku |
