How to convert successive numbers after caret to superscript with jquery?

南楼画角 提交于 2019-12-12 18:28:59

问题


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.


回答1:


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('');
}


来源:https://stackoverflow.com/questions/14833895/how-to-convert-successive-numbers-after-caret-to-superscript-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!