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:
- If there is no bracket behind the caret, only superscript the next character.
- 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.
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