Parser: How to Turn a JavaScript String into One Line of JavaScript?

javascript, jquery

Solution

Use a regular expression with the "global" flag set:

txt.replace(/\n/g, "");

However, you should be careful about removing linebreaks in Javascript. You might break code that was depending on semicolon insertion. Why don't you use an off-the shelf parser like Esprima?

Problem

I'm trying to make a parser for formatting JavaScript in a contextual format. First I want to be able to convert the input JavaScript into one line of JavaScript and then format the code based on my requirements. This does not remove all of the enters or white space: ``` txt = $.trim(txt); txt = txt.replace("\n", ""); ``` How can I convert the text into one line?

Original source