Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 消除注释 #23

Open
sunhengzhe opened this issue May 24, 2018 · 4 comments
Open

javascript 消除注释 #23

sunhengzhe opened this issue May 24, 2018 · 4 comments

Comments

@sunhengzhe
Copy link
Member

实现一个简单的注释去除函数,能够根据指定的注释标记去掉文本中每行的注释,包括行尾的空格

如:

// 输入
apples, pears # and bananas
grapes
bananas !apples

// 输出
apples, pears
grapes
bananas

调用方法为:

var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// 输出 "apples, pears\ngrapes\nbananas"
@KingJeason
Copy link
Member

const solution = function (strs, array) {
    let str = array.reduce((a, b) => {
        return a + '|' + b
    })
    str = '(' + str + ')'
    const re = new RegExp(str + '.*\\n?', 'gim')
    let res = strs.replace(re, function (match) {
        const lastChar = match[match.length -1]
        return lastChar === '\n' ? '\n' : ''
    })
    return res
}
let result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
console.log(result)

@ThoughtZer
Copy link

@KingJeason 如果要去除行尾空格的话,是不是要

let str = array.reduce((a, b) => {
     return '\\s*' + a + '|' + '\\s*' + b
})
把注释符号前面的那个空格匹配下?

@KingJeason
Copy link
Member

@ThoughtZer 感觉也可以有,不过个人感觉不是每个人都按照注释规范来书写的。

@sunhengzhe
Copy link
Member Author

function solution(str, flags) {
    return str.replace(new RegExp(`(\\s*[${flags.join('|')}].*)\\n?`, 'g'),  '\n');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants