Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!