将类添加到数字的第 n 位 [英] Adding Class to the nth Digit of Numbers
问题描述
有一个很好的方法在这个答案中 用于为页面中的每个数字添加一个 span
.
There is a nice way in this answer for adding a span
to every number in the page.
var regex = /(\d+)/,
replacement = '<span>$1</span>';
function replaceText(el) {
if (el.nodeType === 3) {
if (regex.test(el.data)) {
var temp_div = document.createElement('div');
temp_div.innerHTML = el.data.replace(regex, replacement);
var nodes = temp_div.childNodes;
while (nodes[0]) {
el.parentNode.insertBefore(nodes[0],el);
}
el.parentNode.removeChild(el);
}
} else if (el.nodeType === 1) {
for (var i = 0; i < el.childNodes.length; i++) {
replaceText(el.childNodes[i]);
}
}
}
replaceText(document.body);
是否可以将 span
添加到数字的每三位?我的意思是,不使用 Lettering.js.
Is it possible to add a span
to the every third digit of the numbers? I mean, without using Lettering.js.
编辑
@thg435 已经回答了这个问题,但我发现他的第二个正则表达式 /\d(?=\d\d(\d{3})*\b
不适用于阿拉伯语我正在研究的数字.(阿拉伯数字从٠"到٩"开始,在正则表达式中可以被称为 [٠-٩].)可能,问题出在 \b
在第二个正则表达式的末尾.
@thg435 has already answered the question, but I dicovered that his second regex /\d(?=\d\d(\d{3})*\b
does not work on Arabic numbers, which I'm working on. (Arabic numbers start from "٠" to "٩", and can be reffered as [٠-٩] in regex.) Probably, the problem is with the \b
at the end of the second regex.
另外,作为我正在尝试/希望实现的一个例子,١٢٣٤
应该变成 ١٢٣٤
.
Also, as an example of what I'm trying/hoping to achieve, ١٢٣٤
should be turn into ١<span>٢</span>٣٤
.
推荐答案
如果我理解正确
html = text.replace(/(\d\d)(\d)/g, function($0, $1, $2) {
return $1 + "<span>" + $2 + "</span>" })
这将替换右边的每三个数字:
This replaces every third digit from the right:
> a = "foo 1234567890 bbb 123456"
"foo 1234567890 bbb 123456"
> a.replace(/\d(?=\d\d(\d{3})*\b)/g, "[$&]")
"foo 1[2]34[5]67[8]90 bbb [1]23[4]56"
对于阿拉伯数字,请考虑:
For arabic digits consider:
String.prototype.reverse = function() { return this.split("").reverse().join("") }
result = str.replace(/[\u0660-\u0669]+/g, function(s) {
return s.
reverse().
replace(/(..)(.)/g, "$1aaa$2zzz").
reverse().
replace(/zzz(.)aaa/g, "<span>$1</span>")
})
它相当麻烦,但似乎有效:http://jsfiddle.net/VSTJs/2/一个>
It's rather cumbersome, but appears to work: http://jsfiddle.net/VSTJs/2/
这篇关于将类添加到数字的第 n 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!