mrphuzz
mrphuzz

Reputation: 199

Javascript (or jQuery) string replacement

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!

Upvotes: 0

Views: 103

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Easy.

var result = input.replace(/\d([+-]?)/g,function(match,plus) {
    var s = plus ? "sup" : "sub";
    return "<"+s+">"+match+"</"+s+">";
});

Done.

Upvotes: 3

Kokizzu
Kokizzu

Reputation: 26898

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)

Upvotes: 1

Related Questions