javascript - 将部分文本字符串转换为分数

标签 javascript jquery

我有一个字符串,它是产品名称和产品尺寸:

(来源:https://www.bagnboxman.co.uk/product/0215-e-flute-carton-180-x-150-x-370mm-with-50mm-dia-hole/)

Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)

我想把它转换成这样:

Corrugated Box
7⅛ x 5⅞ x 14½" (180 x 150 x 370mm)

为了便于使用,我已将 # 符号放入其中,因此我可以搜索 # 并将其转换为换行符 (br)。

然后我还想寻找英寸分数并将它们转换为适当的..

½

..代码。

我该怎么做呢?今天早上我广泛地搜索了谷歌并尝试了一些东西,但就是无法弄清楚。恐怕我只有基本的 JS 知识。

最佳答案

您可以搜索空格、数字、斜杠和其他数字并返回所需的格式。

var string = 'Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)'

string = string.replace(/\s(\d)\/(\d)/g, '&frac$1$2;').replace('#', '<br>');

document.body.innerHTML += string;

要更改 product-name 类的所有 div,您可以迭代元素。

document.body.onload = function () {
    Array.prototype.forEach.call(document.getElementsByClassName('product-name'), function (element) {
        element.innerHTML = element.innerHTML.replace(/\s(\d)\/(\d)/g, '&frac$1$2;').replace('#', '<br>');
    });
}
<div class="product-name">Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)</div>

关于javascript - 将部分文本字符串转换为分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996080/

相关文章:

javascript - 使用 Ñ 字符(拉丁语)在 PhoneGap 上的 SQLite 中查询不给出结果

java - 如果渲染保存json成功,如何刷新页面true

JavaScript:如何从数组中删除多个键的重复条目

javascript - 使用 AJAX 更新数据表

javascript - SQL不适当的数据填充

javascript - 导航菜单悬停效果仅在特定情况下

javascript - 如何重构这个 for 循环?检查标签 id 是否与数组中的标签匹配,然后更新其边框

javascript - 为什么我的 'menu hide' 代码在我将它放在我的外部脚本文件中时不起作用?

javascript - 如何将表单放入 iframe 中? Visual Studio ,html

javascript - 禁止文件夹 1 从文件夹 2 导入任何内容