首页 > 解决方案 > 一个函数,它接受一行 JavaScript 并返回修剪后的可能行注释

问题描述

如果该行不包含行注释,则应返回 null。

cutComment('let foo; // bar')应该返回'bar',但它返回'let foo; // 酒吧'。

function cutComment(comment) {
  if (comment === null) {
    return null;
  } else {
    return comment.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '').trim();
  }
}

console.log(cutComment('let foo; // bar'));

标签: javascriptstringnullcommentstrim

解决方案


更改正则表达式以匹配之后的任何内容//

function cutComment(comment) {
 if(!comment) return null

 let match = comment.match(/(?<=\/\/).+/)
 if(match.length > 0 ) {
    return match[0]
  }else{
   return null
 }
}

console.log(cutComment('let foo; // bar'));


推荐阅读