Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading