0

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/>
2
  • When do you want to end it? You can replace the _ or ^ with a <sub> Commented Apr 6, 2022 at 18:45
  • At the next non number character- I'll make it clearer in the questions. Commented Apr 6, 2022 at 18:48

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

That works great in most cases: however it doesn't add the closing tag if the string ends with a number, and doesn't add one if there are multiple subscripts in the string
Oh didn't test that will update my answer
what about super scipts? same kind of thing, or is there a different regex expression needed?
Different regex stackoverflow.com/questions/35976910/…. You can combine them with the number one.
thanks! what about negative numbers (just out of curiosity).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.