javascript - 一个函数,它接受一行 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'));
解决方案
更改正则表达式以匹配之后的任何内容//
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'));
推荐阅读
- python - 如何在 Python 字符串中包含转义字符
- mysql - MySQL - 不显示来自 ID 使用的任何行
- scala - 在 rdd 中使用 scala 过滤器功能时的问题
- amazon-web-services - AWS CloudFormation 密钥不接受特殊字符
- html - 为什么 HTML5 中的一些新元素仍然应用了演示文稿?
- android - Kotlin 编写了一个函数来检查潜在的几十个值并返回它们的非空值与 lambda 类型
- bash - 解压 .tar.gz 并修改结果文件
- amazon-web-services - 有没有办法就哪个 VPC 是默认 VPC 向 CloudFormation 撒谎?
- javascript - Ngx-graph 没有正确显示节点和边
- reactjs - prisma中嵌套类型的相应graphql-tag突变