How to convert numbers after caret to superscript with jquery

冷暖自知 提交于 2019-12-07 00:50:30

I don't think this is a job for jQuery. Iterating through the text with plain javascript, though verbose, might be the best way to go:

function superify(input) {
    if(!input) return input;

    var output = [];
    var buffer;
    for(var i=0;i<input.length;i++) {
        var current = input[i];

        if(buffer) {
            if(current === ')') {
                buffer.push('</sup>');
                output.push.apply(output, buffer);
                buffer = null;
            } else {
                buffer.push(current);
            }
        }
        else if(current === '^') {
            var next = input[++i]; 
            if(next === '(') {
                buffer = ['<sup>'];
            } else {
                output.push.apply(output, ['<sup>', next, '</sup>']);
            }   
        } else {
            output.push(current);
        }
    }

    return output.join('');
}

(Code not well-tested. Ran it through couple of examples and it seems to have worked)

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