RegEx for parsing chemical formulas in paragraph
Posted on October 11, 2018 • 1 minutes • 117 words
Here what it is
Data returns something like this
[
{
name: "Water",
details: " water chemical formula is H2O"
}
...
]
and we want to replace chemical formula to look in html like this
water chemical formula is H2O
<p>
water chemical formula is H<sub>2</sub>O
</p>
You can replace the specific content in side the html body like the following.
Link to codepen
var str = 'Aluminium oxide or aluminum oxide is a chemical compound of aluminium and oxygen with the chemical formula Al2O3. It is the most commonly occurring of several aluminium oxides, and specifically identified as aluminium(III) oxide';
var regex = /[A-Z][a-z]?\dW*/g;
str = str.replace(regex, function(matched){
return matched.replace(/\d+/g,function(mtch){
return "<sub>"+mtch+"</sub>";
});
});
document.write(str)