问题
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);
Is it possible to add a span
to the every third digit of the numbers? I mean, without using Lettering.js.
Edit
@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>٣٤
.
回答1:
If I understood correctly
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>")
})
It's rather cumbersome, but appears to work: http://jsfiddle.net/VSTJs/2/
来源:https://stackoverflow.com/questions/16229634/adding-class-to-the-nth-digit-of-numbers