TomKing9 2021-04-15 20:43 采纳率: 77.8%
浏览 43
已采纳

charCodeAt(0)为什么直接把字符串'JavaScripts 中国'遍历了一边?

// 该程序是对字符串进行自定义编码
var toUnicode = String.prototype.toUnicode =function () {
    /* console.log(this);
    console.log(arguments); */
    var _this = arguments[0] || this;
    function f () {
        console.log(arguments[0].charCodeAt(0));
        return '&#'+arguments[0].charCodeAt(0) + ';';
    }
    return _this.replace(/[^\u00-\uFF]|\w/gmi, f);
    
};
var s='JavaScripts 中国';
s = toUnicode(s);   //global调用
console.log(s);

输出结果:JavaScripts 中国

求大佬解释解释,不是很明白了

  • 写回答

1条回答 默认 最新

  • 崽崽的谷雨 2021-04-16 11:22
    关注
    var toUnicode = String.prototype.toUnicode =function () {
        /* console.log(this);
        console.log(arguments); */
        var _this = arguments[0] || this;
        function f () {
            console.log(arguments[0].charCodeAt(0),"000");
            return '&#'+arguments[0].charCodeAt(0) + ';';
        }
        return _this.replace(/[^\u00-\uFF]|\w/gmi, f);
        //return _this.replace(/[^\u00-\uFF]|\w/mi, f); replace的正则有全局和没全局的区别  因为全都匹配正则所以遍历了一遍
    };
    var s='JavaScripts 中国';
    s = toUnicode(s);   //global调用
    console.log(s);
    
    let str="aabbccabxc";
    let v=str.replace(/c/,"v");
    //let v=str.replace(/c/g,"v");正则有了g匹配的全局

    因该是正则你家了全局匹配了/[^\u00-\uFF]|\w/gmi   你改成这样/[^\u00-\uFF]|\w/mi  因为全都能匹配上所以就都遍历了  。仔细看看replace api。

    https://www.w3school.com.cn/js/jsref_replace.asp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统