Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
Text replacing in ReactJS

I am currently working on some code that gets the text (from the cms) in a textblock and replaces so called 'dynamic words' that are defined in the CMS, so when you click a 'dynamic word' it gives you an alert. I now have this code but it doesn't work and it did work with hardcoded text instead of dynamic words from the CMS. Can anyone see where the problem is here?

For extra info leave an message ( For example if you need to know what an specified console.log gives back :) )

import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';

export const ArticleBodyText = ({ item, dynamic_words }) => {
  useEffect(() => {
    const el = document.getElementById('this-text');
    const text = el.innerHTML;
    dynamic_words.map(word => {
      const dynamic_word = word.word?.[0].text;
      const newText = text.replace(
        `/\b${dynamic_word}\b/g`,
        `<span class='dynamic-word'>${dynamic_word}</span>`
      );
      el.innerHTML = newText;
      const spans = el.querySelectorAll('.dynamic-word');
      for (let i = 0; i < spans.length; i += 1) {
        spans[i].addEventListener(
          'click',
          function () {
            if (this.innerHTML === dynamic_word) {
              alert('You clicked a dynamic word!');
            }
          },
          false
        );
      }
    });
  });

  return item?.primary?.body_text.map(bodytext => (
    <TextBlock
      id="this-text"
      key={bodytext.text}
      dangerouslySetInnerHTML={{ __html: bodytext.text }}
    />
  ));
};

EDIT: Working version:

import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';

export const ArticleBodyText = ({ item, dynamic_words }) => {
  useEffect(() => {
    const el = document.getElementById('this-text');
    const text = el.innerHTML;
    const newText = text.replace(/\bte\b/g, "<span class='dynamic-word'>te</span>");
    el.innerHTML = newText;
    const spans = el.querySelectorAll('.dynamic-word');
    for (let i = 0; i < spans.length; i += 1) {
      spans[i].addEventListener(
        'click',
        function () {
          if (this.innerHTML === 'te') {
            alert('Je hebt op een dynamic word geklikt!');
          }
        },
        false
      );
    }
  });

  return item?.primary?.body_text.map(bodytext => (
    <TextBlock
      id="this-text"
      key={bodytext.text}
      dangerouslySetInnerHTML={{ __html: bodytext.text }}
    />
  ));
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This way you can create dynamic regex

const word = "something";
const sentence = "This is something";

let first = "\\b",
  second = "\\b";

const regex = new RegExp(first + word + second, "g");

const newSent = sentence.replace(regex, "Inder");
console.log(newSent);

about 4 years ago · Juan Pablo Isaza Relatório

0

replace expects a regular expression or a string (exact match, not a string that looks like a regular expression). You will need to create a regex from a template literal:

const oldText = "the sly brown fox is sly"
const dynamic_word = "sly"
const newText = oldText.replaceAll(
  new RegExp(`\\b${dynamic_word}\\b`, 'g'),
  `<span class='dynamic-word'>${dynamic_word}</span>`
);

console.log(newText)

Note:

  • The \b word break flag needs to be escaped in the template literal
  • You must use the g flag or it will only replace the first occurrence
about 4 years ago · Juan Pablo Isaza Relatório

0

Fixed it, I changed it to:

const dynamic_word = word.word?.[0].text;
      const first = '\\b';
      const second = '\\b';
      const regex = new RegExp(first + dynamic_word + second, 'g');
      const newText = text.replace(regex, `<span class="dynamic-word">${dynamic_word}</span>`);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda