我有一个字符串,它是产品名称和产品尺寸:
(来源:https://www.bagnboxman.co.uk/product/0215-e-flute-carton-180-x-150-x-370mm-with-50mm-dia-hole/)
瓦楞纸箱#7 1/8 x 5 7/8 x 14 1/2"(180 x 150 x 370mm)
我想把它转换成这个:
瓦楞纸箱
7⅛x5⅞x14½"(180 x 150 x 370mm)
我已经将#符号放入以便于使用,因此我可以搜索#并将其转换为换行符(br).
然后我还想寻找英寸分数并将它们转换为适当的..
½
..码.
我该怎么做呢?我今天早上广泛地谷歌并尝试了一些事情,但只是无法解决这个问题.我害怕我只有基本的JS知识.
Nin*_*olz 12
您可以搜索空格,数字,斜线和其他数字并返回所需的格式.
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;Run Code Online (Sandbox Code Playgroud)
要更改类的所有div product-name,可以迭代元素.
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>');
});
}Run Code Online (Sandbox Code Playgroud)
<div class="product-name">Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)</div>Run Code Online (Sandbox Code Playgroud)
这是一个更灵活的解决方案,不依赖于有限的实体集&fracXY;。相反,它使用“分数斜线”字符⁄:
jQuery('.product-name').html( // Set the HTML of all
function () { // .product-name elements to:
return jQuery(this) // The current element's
.html() // HTML,
.replace( // Where we replace
/ ?(\d+)\/(\d+)/g, // A space, number-slash-number
"<sup>$1</sup>⁄<sub>$2</sub>" // With a fraction.
);
}
);Run Code Online (Sandbox Code Playgroud)
sup { color: red; }
sub { font-style: italic; }Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-name">
Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)
<br />
And a random fraction 12345/67890
</div>Run Code Online (Sandbox Code Playgroud)
另一个优点是您可以单独设计分数的各个部分。
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |