[英]How can I reformat 1 1/2 into pretty fraction HTML using regex and javascript
I have a string like 5 1/36
that I want to rewrite as 5 <sup>1</sup>⁄<sub>36</sub>
. 我有一个像
5 1/36
这样的字符串,我想将其重写为5 <sup>1</sup>⁄<sub>36</sub>
。 Before the fraction, there can either be nothing or a space, and after the fraction there can either be a space or nothing. 在小数之前,可能没有任何内容或有空格,在小数之后可能没有空间或没有任何内容。 A string could contain multiple fractions.
一个字符串可以包含多个分数。 The fractions may be positive or negative.
分数可以是正数或负数。
example: 例:
myString = '(1 3/4)÷(-2/3)-(-6)-(6)-(1)+(-4)';
Like this: 像这样:
var regex = /(\d+)\/(\d+)/g;
var myString = "(1 3/4)÷(-2/3)-(-6)-(6)-(1)+(-4)";
var myResult = myString.replace(regex, "<sup>$1</sup>⁄<sub>$2</sub>");
// "(1 <sup>3</sup>⁄<sub>4</sub>)÷(-<sup>2</sup>⁄<sub>3</sub>)-(-6)-(6)-(1)+(-4)"
一个简单的字符串替换数字有关/
应该可以解决问题
str = str.replace(/\b(\d+)\/(\d+)/g, '<sup>$1</sup>⁄<sub>$2</sub>');
Here's a working example: 这是一个工作示例:
myString = '(1 3/4)÷(-2/3)-(-6)-(6)-(1)+(-4)'; document.write(myString.replace(/(\\d+)(\\/)(\\d+)/g, '<sup>$1</sup>⁄<sub>$3</sub>'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.