 <h2>AST</h2> <p>To avoid any chance of error in code manipulation using an <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">Abstract Syntax Tree (AST)</a> type solution is best. One example implementation is in <a href="https://github.com/mishoo/UglifyJS2" rel="nofollow">UglifyJS2</a> which is a JavaScript parser, minifier, compressor or beautifier toolkit.</p> <h2>RegEx</h2> <p>Alternatively if an AST is over the top for your specific task you can use RegEx.</p> <p>But do you have to contend with comments too?</p> <p>The process might look like this:</p> <ol> <li>Use a carefully formed regex to <strong>split</strong> the JavaScript code string based on these in this order: <ul> <li>comment blocks</li> <li>comment lines</li> <li>quoted strings both single and double quotes (remembering to contend with escaping of characters).</li> </ul></li> <li>Iterate though the split components. If string (beings with <code>"</code> or <code>'</code>) or comment (begins with <code>//</code> or <code>/*</code>) ignore, otherwise run your replacement.</li> <li>(and the simple part) join array of strings back together.</li> </ol>