Question

This question is related to How to convert numbers after caret to superscript with jquery where I got a very good answer.

Problem now, I need to extend the recent script | jsfiddle so that it takes successive numbers into account.

The recent script takes a string, and checks it for carets. Then:

  1. If there is no bracket behind the caret, only superscript the next character. x^2 becomes x<sup>2</sup>
  2. If there is an opening bracket, superscript until the closing bracket. x^(2y+1) becomes x<sup>2y+1</sup>

However, I need to extend n°1 as there might be a number holding several digits or even variables.

So we need a new n°1:

  1. If there is no bracket behind the caret, superscript all successive characters as long as they are numbers or characters. So that x^12a becomes x<sup>12a</sup>

I tried to implement it, including a variable afternext = input[ (i+1) ]) and checking this char by if(afternext.match(/^[0-9a-zA-Z]+$/)) { ... } storing it, but I failed :(

So if anyone feels fit enough today, I'd be happy to see your solution for that.

Thank you.

Was it helpful?

Solution

Here you go, sir. I refactored it a bit to use an inner loop instead of a buffer array, since it got a bit messy with the additional buffering condition.

// transform carets, e.g. x^2 to x<sup>2</sup> and x^(2y) to x<sup>2y</sup>
function superify(input) {
    if(!input) return input;
    var output = [];
    var alphanumeric = /^[a-z0-9]+$/i;
    var i = 0;
    var parens;

    //outer loop for iterating string
    while(i < input.length) {
        var current = input[i++];
        var next    = input[i];

        if(current === '^' && next && ((parens = (next === '(')) || next.match(alphanumeric))) {

            var first = next;

            //start super
            output.push('<sup>');
            if(!parens) 
                output.push(first);

            //push chars to output until break or string end
            while(i++ < input.length) {
                current = input[i];
                if(parens && current === ')')
                    break;
                if(!parens && !current.match(alphanumeric))
                    break;
                output.push(current);
            }

            output.push('</sup>');
            if(!parens) 
                output.push(current);
            i++;
        }
        else {
            output.push(current);
        }
    }

    return output.join('');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top