How to convert numbers after caret to superscript with jquery

被刻印的时光 ゝ 提交于 2019-12-08 08:36:46

问题


A lot of users on our maths forum enter n-th power with caret symbol, e.g. x^(4y).

We would like to replace the caret symbol and use superscript instead, wrapping the numbers and variables right after the caret. So that x^(4y) becomes x(4y).

Rules:

  1. If there is no bracket behind the caret, only superscript the next character.
  2. If there is an opening bracket, superscript until the closing bracket.

Here is a post with different caret versions.

Of course there are many js-libraries out there that we could use, but isn't it possible to do this single text converting task with jquery?

Has anybody build something like that already?

Thank you.


回答1:


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)



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

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