Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 493
Jason Biondo Avatar asked May 24 '26 13:05

Jason Biondo


2 Answers

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?

like image 79
hugomg Avatar answered May 26 '26 04:05

hugomg


Use :

  • \s character that represents any space character (Carriage return, Line Feed, Tabs, Spaces, ...)
  • the "greedy" g flag.

    var text = txt.replace(/\s+/g, ' ');

Hope it helps

like image 40
php-dev Avatar answered May 26 '26 05:05

php-dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!