·您当前的位置:首页 > 技术教程 > JavaScript >

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

时间:2015-08-11 16:02酷播
js 如何删除一段代码中的所有注释内容

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

  1. function removeJsComments(code)   {     
  2.     return code.replace(/(?:^|\n|\r)\s*\/\*[\s\S]*?\*\/\s*(?:\r|\n|$)/g, '\n').replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '\n');   

 

  1. function removeComments(str) { 
  2.   
  3.     var uid = '_' + +new Date(), 
  4.         primatives = [], 
  5.         primIndex = 0
  6.   
  7.     return ( 
  8.         str 
  9.         /* Remove strings */ 
  10.         .replace(/(['"])(\\\1|.)+?\1/g, function(match){ 
  11.             primatives[primIndex] = match; 
  12.             return (uid + '') + primIndex++; 
  13.         }) 
  14.   
  15.         /* Remove Regexes */ 
  16.         .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){ 
  17.             primatives[primIndex] = $2; 
  18.             return $1 + (uid + '') + primIndex++; 
  19.         }) 
  20.   
  21.         /* 
  22.         - Remove single-line comments that contain would-be multi-line delimiters 
  23.             E.g. // Comment /* <-- 
  24.         - Remove multi-line comments that contain would be single-line delimiters 
  25.             E.g. /* // <-- 
  26.        */ 
  27.         .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '') 
  28.   
  29.         /* 
  30.         Remove single and multi-line comments, 
  31.         no consideration of inner-contents 
  32.        */ 
  33.         .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '') 
  34.   
  35.         /* 
  36.         Remove multi-line comments that have a replaced ending (string/regex) 
  37.         Greedy, so no inner strings/regexes will stop it. 
  38.        */ 
  39.         .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '') 
  40.   
  41.         /* Bring back strings & regexes */ 
  42.         .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){ 
  43.             return primatives[n]; 
  44.         }) 
  45.     ); 
  46.   

 

热门文章推荐

请稍候...

保利威视云平台-轻松实现点播直播视频应用

酷播云数据统计分析跨平台播放器