Replace multiple specific words in a static string literal with JSX

Attempting to replace specific words in a static string literal with JSX example and getting an expected side effect. Only one specific word out of the multiple words takes effect.

import "./styles.css";

const Button = ({ children }) => <button>{children}</button>;

const text = "some text with the word email and call in it";

export default function App() {
  const nodes = text
    .split(new RegExp(`(\\b${"email" && "call"}\\b)`, "i"))
    .map((node, i) => (i % 2 ? <Button>{node}</Button> : node));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>{nodes}</p>
    </div>
  );
}

Also I tried to map over the words like so:

import "./styles.css";

const Button = ({ children }) => <button>{children}</button>;

const words = ["email", "call"];

const text = "some text with the word email and call in it";

export default function App() {
  const nodes = text
    .split(new RegExp(`(\\b${words.map((word) => word)}\\b)`, "i"))
    .map((node, i) => (i % 2 ? <Button>{node}</Button> : node));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>{nodes}</p>
    </div>
  );
}

code pen

>Solution :

You’ll want to use regular express alternation to match any of several words.

If you’re just hard-coding the words to replace use the following simplified expression…

text.split(/\b(email|call)\b/i);

Otherwise, if you have an array of words, something like this should work

text.split(new RegExp(`\\b(${words.join("|")})\\b`, "i"));

The word-boundaries \b prevent you from accidentally matching words containing the searches like "emailing" or "calling".

Edit dazzling-solomon-hg7ixu

Leave a Reply