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

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

报告相同问题?