Home > Mobile >  React convert a string into element with sub and super scripts
React convert a string into element with sub and super scripts

Time:04-08

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/>

CodePudding user response:

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, ""));

  • Related