How to replace numbers in body to Persian numbers?
You can use this method: (http://jsfiddle.net/A4NfG/1/)
persian={0:'۰',1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹'};
function traverse(el){
if(el.nodeType==3){
var list=el.data.match(/[0-9]/g);
if(list!=null && list.length!=0){
for(var i=0;i<list.length;i++)
el.data=el.data.replace(list[i],persian[list[i]]);
}
}
for(var i=0;i<el.childNodes.length;i++){
traverse(el.childNodes[i]);
}
}
There is this findAndReplaceDOMText.js that may help you. It walks through all nodes in the document (as opposed to all elements) and replaces the text when the nodeType
argument equals 3, which is TEXT_NODE.
This example will replace numbers in the whole page:
function walkNode(node) {
if (node.nodeType == 3) {
// Do your replacement here
node.data = node.data.replace(/\d/g,convert);
}
// Also replace text in child nodes
for (var i = 0; i < node.childNodes.length; i++) {
walkNode(node.childNodes[i]);
}
}
walkNode(document.getElementsByTagName('body')[0]);
function convert(a){
return ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'][a];
}
See JavaScript String.replace
documentation here.
If you want to select some elements by a selector
, you can use this simple code (JsFiddle):
persian={0:'۰',1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹'};
$(".persian-digit").each(function(){
for(var i=0;i<=9;i++) {
var re = new RegExp(i,"g");
$(this).html($(this).html().replace(re,persian[i]));
}
});
Then for use it:
<span class="persian-digit">This span contains persian digits (0123456789),</span>
<span>and this one contains english digits (0123456789).</span>
I wrote this short and simple code.
// ES6
const regex = /[۰-۹]/g
let str = '۰۱۲۳۵۴۸۹۰۷۸۹۰۱۲';
let result = str.replace(regex, function (w) {
return String.fromCharCode(w.charCodeAt(0) - 1728)
}
)
console.log(result);
If you wanna use it on a specific element or selector, this might help :
var persian = Array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
function replaceDigits(selector) {
for(i=0;i<10;i++){
var regex=eval("/"+i+"/g");
$(selector).html($(selector).html().replace(regex,persian[i]));
}
}
replaceDigits(".selected");
Worked for me!