问答一下,轻松解决,电脑应用解决专家!
主板显卡CPU内存显示器
硬盘维修显卡维修显示器维修
注册表系统命令DOS命令Win8
存储光存储鼠标键盘
内存维修打印机维修
WinXPWin7Win10/Win11
硬件综合机箱电源散热器手机数码
主板维修CPU维修键盘鼠标维修
Word教程Excel教程PowerPointWPS
网络工具系统工具图像工具
数据库javascriptLinux系统
PHP教程CSS教程XML教程

js删除一段代码中的所有注释内容

更新时间:2021-07-29 13:28 作者:佚名点击:
//方法一
function removeJsComments(code)   {     
return code.replace(/(?:^|\n|\r)\s*\/\*[\s\S]*?\*\/\s*(?:\r|\n|$)/g, '\n').replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '\n');   
}
//方法二
function removeComments(str) { 
    var uid = '_' + +new Date(), 
        primatives = [], 
        primIndex = 0; 
    return ( 
        str 
        /* Remove strings */ 
        .replace(/(['"])(\\\1|.)+?\1/g, function(match){ 
            primatives[primIndex] = match; 
            return (uid + '') + primIndex++; 
        }) 
  
        /* Remove Regexes */ 
        .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){ 
            primatives[primIndex] = $2; 
            return $1 + (uid + '') + primIndex++; 
        }) 
  
        /* 
        - Remove single-line comments that contain would-be multi-line delimiters 
            E.g. // Comment /* <-- 
        - Remove multi-line comments that contain would be single-line delimiters 
            E.g. /* // <-- 
       */ 
        .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '') 
  
        /* 
        Remove single and multi-line comments, 
        no consideration of inner-contents 
       */ 
        .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '') 
  
        /* 
        Remove multi-line comments that have a replaced ending (string/regex) 
        Greedy, so no inner strings/regexes will stop it. 
       */ 
        .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '') 
  
        /* Bring back strings & regexes */ 
        .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){ 
            return primatives[n]; 
        }) 
    ); 
} 
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
你可能感兴趣的内容