Issue
https://codesandbox.io/s/gifted-leftpad-ck6k9s?file=/src/App.tsx
Must be done through the method replace,highlighting letters or words while maintaining their case, and the search string can be any
Now the selection works in such a way that it changes the original letters, for example, if you make a selection by letter 'P' then all letters 'P' become capital letters. It is necessary to make the letters remain as they were originally, but the highlighting works in case-independent. Where the big letter remained large where the small remained small.
in fact, I am doing an analogue of highlighting in the browser through controll f
DataHighlighting.tsx
interface Props {
data: string;
searchString: string;
}
const DataHighlighting = ({ data, searchString }: Props): JSX.Element => {
const regex = new RegExp(searchString, "gi");
return (
<span
dangerouslySetInnerHTML={{
__html: data.replace(
regex,
`<span style="background: #ff0">${searchString}</span>`
)
}}
></span>
);
};
export default DataHighlighting;
App.tsx
import "./styles.css";
import DataHighlighting from "./DataHighlighting";
export default function App() {
return (
<div className="App">
Programming learning programming for Programming up
<div />
<DataHighlighting
data={"Programming learning programming for Programming up"}
searchString={"P"}
/>
<div />
<DataHighlighting
data={"Programming learning programming for Programming up"}
searchString={"programming"}
/>
<div />
</div>
);
}
Solution
Here is your solution: https://codesandbox.io/s/regex-case-vr2jxk?file=/src/DataHighlighting.tsx
And here is the summary:
data.replace(
regex,
(match) => `<span style="background: #ff0">${match}</span>`
)
Use the callback to get what you are replacing; instead of replacing it with your argument, use that callback value, which is case-sensitive.
Complete code, for your convenience:
interface Props {
data: string;
searchString: string;
}
const DataHighlighting = ({ data, searchString }: Props): JSX.Element => {
const regex = new RegExp(searchString, "ig");
return (
<span
dangerouslySetInnerHTML={{
__html: data.replace(
regex,
(match) => `<span style="background: #ff0">${match}</span>`
)
}}
></span>
);
};
export default DataHighlighting;
And:
import "./styles.css";
import DataHighlighting from "./DataHighlighting";
export default function App() {
return (
<div className="App">
Programming learning programming for Programming up
<div />
<DataHighlighting
data={"Programming learning programming for Programming up"}
searchString={"P"}
/>
<div />
<DataHighlighting
data={"Programming learning programming for Programming up"}
searchString={"programming"}
/>
<div />
</div>
);
}
Answered By - Maifee Ul Asad


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.