最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Parser: How to Turn a JavaScript String into One Line of JavaScript? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Feb 5, 2014 at 20:39 Jason BiondoJason Biondo 8345 gold badges18 silver badges37 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

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?

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

If the text es from some operating systems, it may have the \r\n line ending, so it is worth removing both...

You should also use /\r/g this replaces ALL \rs not just the first one.

var noNewLines = txt.replace(/\r/g, "").replace(/\n/g, "");

You have to be pretty sure there are no single-line ments and that there are no missing semi-colons.

You can try to minify your code, using something like https://javascript-minifier./ however this will also change your variable names

发布评论

评论列表(0)

  1. 暂无评论