So, I have strings pulled from a JSON array like this:
Hg22+
CO32-
Al3Cl23+
These numbers need to be superscript or subscript, with rules. It's only numbers 0-9, and if that number has a plus or minus after it, it needs to be superscript, meaning I need to change the string to <sup>3+</sup>. All other numbers, if they haven't been superscripted, need to be subscripted. Here are a few examples of what I need:
C12H22O11 (s, sucrose) = <sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub> (s, sucrose)
Al3Cl23+ = Al<sub>3</sub>Cl<sub>2</sub><sup>3+</sup>
Hg22+ = Hg<sub>2</sub><sup>2+</sup>
I can do it, but very sloppily. I am really open to a good way to change string like above. If anyone can help out I'd be really appreciative!
Thanks!
-
How are you currently solving this, and what's wrong with that code? Please edit that into your question.Nathan Tuggy– Nathan Tuggy2015年01月31日 00:28:46 +00:00Commented Jan 31, 2015 at 0:28
-
I didn't implement it, because I know it would have been completely gross and unwieldy. Definitely couldn't have used regex on my own, and I knew regex would be by far the best way to go.mrphuzz– mrphuzz2015年01月31日 23:37:30 +00:00Commented Jan 31, 2015 at 23:37
2 Answers 2
Easy.
var result = input.replace(/\d([+-]?)/g,function(match,plus) {
var s = plus ? "sup" : "sub";
return "<"+s+">"+match+"</"+s+">";
});
Done.
1 Comment
Slightly modified from @Niet the Dark Absol's answer
var tests = ['Hg22+', 'CO32-', 'Al3Cl23+','C12H22O11 (s, sucrose)'];
function chemize(input) {
return input.replace(/\d([\+\-]?)/g,function(match,plus) {
var s = plus ? "sup" : "sub";
return "<"+s+">"+match+"</"+s+">";
});
}
for(var z in tests) {
var test = tests[z];
console.log('"' + test + '" --> ' + chemize(test) );
}
Output:
"Hg22+" --> Hg<sub>2</sub><sup>2+</sup>
"CO32-" --> CO<sub>3</sub><sup>2-</sup>
"Al3Cl23+" --> Al<sub>3</sub>Cl<sub>2</sub><sup>3+</sup>
"C12H22O11 (s, sucrose)" --> C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub> (s, sucrose)
3 Comments
- (minus sign) and g (global replace)