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

156
Visualizações
React convert a string into element with sub and super scripts

I'm trying to make a functional component that basically converts ^ and _ characters in a string to sub and super scripts. Here are some examples.

'example_3' -> <h1>example<sub>3<sub/><h1/>

should start a tag at a '_' or '^' and close the tag at the next non-number character.

'another_1234Example' -> <h1>another<sub>1234<sub/>Example<h1/>

also should be able to work for any amount of numbers

'something^2else_34' -> <h1>something<sup>2<sub/>else<sub>34<sub/> <h1/>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Solution 1 (over complicated):

const string = "another_1234Example_348jiwf_342";

console.log(
  (string.trim() + " ")
    .split("_")
    .join("<sub>")
    .split(/(?<=<sub>\d+)(?!\d)/g)
    .join("</sub>")
);

Split _ this will return an array, join a <sub> after that. Than check with regex if it matches a number with a start <sub>.

Link to regex: https://regex101.com/r/RFkEQa/1

Solution 2 (recommend):

It's better to use replace for this kind of stuff. Referring to this post: https://stackoverflow.com/a/50463993/8273193

const string = "another_1234Example_348jiwf_342";
console.log(string.replace(/(_\d+)/g, "<sub>$&</sub>").replace(/_/g, ""));

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