UNPKG

als-remove-js-comments

Version:

A utility for removing JavaScript comments, supporting both single-line and multi-line comments with proper handling of string literals.

24 lines (22 loc) 1.03 kB
function removeComments(text) { const quotes = { '"': true, "'": true, '`': true }; let newText = '', quote = null; for (let i = 0; i < text.length; i++) { const char = text[i]; if (quotes[char] && text[i - 1] !== '\\') { quote = quote === char && text[i - 1] !== '\\' ? null : char; newText += text[i]; } else if (!quote && char === '/' && text[i + 1] === '/') { while(i < text.length && text[i] !== '\n') i++; if(text[i] === '\n') newText += text[i] } else if (!quote && char === '{' && text[i + 1] === '/' && text[i + 2] === '*') { while (i < text.length && !(text[i] === '*' && text[i + 1] === '/' && text[i + 2] === '}')) i++; i = i+2 } else if (!quote && char ==='/' && text[i + 1] === '*') { while(i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++; i++ } else newText += text[i] } return newText } try { module.exports = removeComments } catch (error) { }