javascript 如何将正文中的数字替换为波斯数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15247405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:02:43  来源:igfitidea点击:

how to replace numbers in body to persian numbers?

javascriptjqueryhtml

提问by Alireza41

I want to convert every numbers on html content to Persian numbers without effect on page element.

我想将 html 内容上的每个数字都转换为波斯数字而不影响页面元素。

for example:

例如:

<div style='color: #c2c2c2'>
  text number 1
  <span>text number 2</span>
  <div>
    text number 3
    <b>text number 4</b>
    <a href='#page2'>text number 5</a>
   </div>
</div>

convert to :

转换成 :

  <div style='color: #c2c2c2'>
  text number ?
  <span>text number ?</span>
  <div>
    text number ?
    <b>text number ?</b>
    <a href='#page2'>text number ?</a>
   </div>
</div>

persian = array('?', '?', '?', '?', '?', '?', '?', '?', '?', '?');
english = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

Thanks.

谢谢。

回答by haitaka

You can use this method: (http://jsfiddle.net/A4NfG/1/)

您可以使用此方法:(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]);
    }
}

回答by Sjoerd

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];
}

回答by Navid Farhadi

If you want to select some elements by a selector, you can use this simple code (JsFiddle):

如果你想通过 a 选择一些元素selector,你可以使用这个简单的代码(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>

回答by mcrunix

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);

回答by Sjoerd

There is this findAndReplaceDOMText.jsthat may help you. It walks through all nodes in the document (as opposed to all elements) and replaces the text when the nodeTypeargument equals 3, which is TEXT_NODE.

有这个findAndReplaceDOMText.js可以帮助你。它遍历文档中的所有节点(而不是所有元素)并在nodeType参数等于 3时替换文本,即TEXT_NODE

回答by Behzad

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!

对我来说有效!

回答by Bashirpour

<script>

    function en2fa(num){
        let arr = [];
        persian = {0:'?',1:'?',2:'?',3:'?',4:'?',5:'?',6:'?',7:'?',8:'?',9:'?'};
        num.split('').map((number,index)=>{
            arr[index] = (persian[number]);
        });
        return arr.join('');
    }

    console.log(en2fa("86598231452"));

</script>

test this code in codepen

在 codepen 中测试此代码

https://codepen.io/bashirpour/pen/JvgeYy

https://codepen.io/bashirpour/pen/JvgeYy

回答by Hamid Tanhaei

all of the ways are not confident because lots of Persian users, use Arabic keyboard and Arabic chars are different with Persian numbers.

所有的方式都不自信,因为很多波斯用户使用阿拉伯语键盘,阿拉伯字符与波斯数字不同。

it's better to replace Arabic chars too.

最好也替换阿拉伯字符。

for example this is zero char in Persian: ? and this is zero char in Arabic: ?

例如,这是波斯语中的零字符:?这是阿拉伯语中的零字符:?

as you see, both are the same but their Unicode are not the same. if you use Persian in your project, i recommend you persian.js, it's just 5 KB.

如您所见,两者都是相同的,但它们的 Unicode 并不相同。如果你在你的项目中使用波斯语,我推荐你persian.js,它只有 5 KB。

or if you don't want to use this library you can use this code:

或者,如果您不想使用此库,则可以使用以下代码:

function convertToPersianNumber(value) {
  const arabicNumbers = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?'];
  const persianNumbers = ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?'];
  const englishNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  let confidentValue = value;
  for (var i = 0; i < value.length; i++) {
    const inArabicIndex = arabicNumbers.indexOf(value[i]);
    if (inArabicIndex > -1) {
    confidentValue = confidentValue.replace(
      value[i],
      englishNumbers[inArabicIndex]
    );
  }

  const inPersianIndex = persianNumbers.indexOf(value[i]);
  if (inPersianIndex > -1) {
      confidentValue = confidentValue.replace(
        value[i],
        englishNumbers[inPersianIndex]
      );
    }
  }
  return confidentValue;
}

回答by behzad soleimani

  try {
    if (!enDigit &&  !enDigit.toString().length)
      return "";

  let enDigitString = typeof enDigit === 'number' ? enDigit.toString() : enDigit;

  var newValue="";
  for (var i=0;i<enDigitString.length;i++)
  {
      var ch=enDigitString.charCodeAt(i);
      if (ch>=48 && ch<=57)
      {
          // european digit range
          var newChar=ch+1728;
          newValue=newValue+String.fromCharCode(newChar);
      }
      else
          newValue=newValue+String.fromCharCode(ch);
  }
  return newValue;

  }catch (e) {
    return "";
  }

回答by webgodo

Just a bit more clear snippet:

更清晰的片段:

function numbersToPersian (el) {
    ['?', '?', '?', '?', '?', '?', '?', '?', '?', '?'].forEach((num, index) => {
        el.textContent = el.textContent.replace(new RegExp(index, 'g'), num);
    });
};

function traverseToLeaf (el) {
    if (el.childNodes.length === 0) return;

    el
        .childNodes
        .forEach(node => {
            if (node.nodeType === 3) {
                numbersToPersian(node);
                } else {
                traverseToLeaf(node);
            }
        });
};

// just write your element class or ID instead of '.primary' in line below
traverseToLeaf(document.querySelector('.primary'));