简体   繁体   English

如何使用正则表达式和JavaScript将1 1/2重新格式化为相当一部分HTML

[英]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>&frasl;<sub>36</sub> . 我有一个像5 1/36这样的字符串,我想将其重写为5 <sup>1</sup>&frasl;<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>&frasl;<sub>$2</sub>");
// "(1 <sup>3</sup>&frasl;<sub>4</sub>)÷(-<sup>2</sup>&frasl;<sub>3</sub>)-(-6)-(6)-(1)+(-4)"

一个简单的字符串替换数字有关/应该可以解决问题

str = str.replace(/\b(\d+)\/(\d+)/g, '<sup>$1</sup>&frasl;<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>&frasl;<sub>$3</sub>')) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试使用HTML Javascript制作分数计算器,我需要简化分数该怎么做? - I am trying to make a Fraction Calculator in HTML Javascript, I need to simplify the fraction how can I do this? 如何使用JavaScript保持分数格式? - How can I keep fraction formatting using JavaScript? 如何使用HTML / CSS / JScrollPane制作漂亮的滚动条 - How can I make pretty scrollbars using HTML/CSS/JScrollPane 在POST之前,如何使用Javascript(或Rails)重新格式化表单输入? - How can I reformat form input before POST using Javascript (or Rails)? 如何使用Javascript从字符串中间提取然后重新格式化文本? - How can I extract and then reformat text from the middle of a string with Javascript? 如何在PhpStorm的JavaScript文件中重新格式化HTML代码 - How to reformat HTML code in JavaScript file in PhpStorm 这是什么时间格式,如何使用JQuery重新格式化? - What time format is this and how can I reformat it using JQuery? 如何使用正则表达式从 javascript 中的 HTML 字符串中删除所有时间戳? - How can I remove all timestamps from HTML string in javascript, using regex? 如何使Vim JavaScript漂亮的格式化程序插件运行? - how can I make the vim javascript pretty formatter plugin run? 如何重新格式化嵌套的 JSON 并使用 javascript 进行重组 - How to reformat a Nested JSON and restructure using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM