charsets replacements issue

This question already has an answer here:

  • How to replace all occurrences of a string in JavaScript? 41 answers

  • By default, replace only replaces the first occurrence. To replace all occurrences use a regular expression with the g flag:

    function en2fa(str){
        string = string.replace(/1/g, '۱');
        string = string.replace(/2/g, '۲');
        // ...
        return string;
    }
    
    var a = '12345';
    alert(en2fa(a.replace(/1/g, '3')));
    

    You can make the translation more concise using a lookup table:

    var en2faDict = {};
    var fa2enDict = {};
    "۰۱۲۳۴۵۶۷۸۹".split('').forEach(function(fa, en) {
        en = "" + en;
        en2faDict[en] = fa;
        fa2enDict[fa] = en;
    });
    
    function translate(str, dict, pattern) {
        return str.replace(pattern, function(c) { return dict[c]; });
    }
    
    function fa2en(str) {
        return translate(str, fa2enDict, /[۰-۹]/g);
    }
    
    function en2fa(str) {
        return translate(str, en2faDict, /[0-9]/g);
    }
    

    Here is a version which may be faster in some browsers. It uses a for-loop and range checking which relies on the fact that the digits are contiguous:

    var en2faDict = {};
    var fa2enDict = {};
    "۰۱۲۳۴۵۶۷۸۹".split('').forEach(function(fa, en) {
        en = "" + en;
        en2faDict[en] = fa;
        fa2enDict[fa] = en;
    });
    en2faDict.low = '0'.charCodeAt(0);
    en2faDict.high = '9'.charCodeAt(0);
    fa2enDict.low = en2faDict['0'].charCodeAt(0);
    fa2enDict.high = en2faDict['9'].charCodeAt(0);
    
    function translate(str, dict) {
        var i, l = str.length, result = "";
        for (i = 0; i < l; i++) {
            if (str.charCodeAt(i) >= dict.low && str.charCodeAt(i) <= dict.high)
                result += dict[str[i]];
            else
                result += str[i];
        }
        return result;
    }
    
    function fa2en(str) {
        return translate(str, fa2enDict);
    }
    
    function en2fa(str) {
        return translate(str, en2faDict);
    }
    

    From clues in your question, Your issue is in the way you are doing the replace. You showed us fa2en , I presume your en2fa is similar. However a better and working implementation would be as follows :

      function en2fa (str) {
        return str.replace (/d/g, function (d) {
          return '۰۱۲۳۴۵۶۷۸۹'.charAt (+d);
        });
      }
    

    You main problem was as described by @tom in your code using string replacement only replaces the first occurrence. @tom 's answer while it might work is not standard. To replace all occurrences you should use a regExp replace with a g modifier. This results in significantly shorter code also !

    链接地址: http://www.djcxy.com/p/16846.html

    上一篇: 如何用replace替换创建一个“bbcode”javascript

    下一篇: charsets替换问题