Question

I'm having trouble writing a function that will take a chemical formula string such as "NiNFe(AsO2)2" and remove one of the elements.
my current attempt is:

pattern = new RegExp(symbol, "g")
formula.replace(pattern, "")

If the symbol is "N" and the formula is "NiNFe(AsO2)2" I end up with "iFe(AsO2)2" instead of the desired "NiFe(AsO2)2". Does anyone know how to code this in such a way that it would distinguish the N from the Ni and replace just that?

Was it helpful?

Solution

RegExp(symbol+'(?![a-z])','g'); will match the symbol if it is not followed by a lower case letter

OTHER TIPS

Use a negative lookahead. The following will also remove any quantifier it may have:

pattern = new RegExp(symbol + "(?![a-z])" + "\d*", "g");

If for some reason you want to avoid using negative lookahead (eg. javascript supports it but some other regex engines don't), you could simply match symbol + "([^a-z])" and replace with $1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top