Home > Software design >  make the same highlight as in the search browser through the method replace
make the same highlight as in the search browser through the method replace

Time:10-08

correct result

wrong result

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>
  );
}

CodePudding user response:

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>
  );
}

  • Related