473,383 Members | 1,877 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Javascript formatter?



I am using a utility that creates Javascript. However the javascript is one
hugely long stream of characters. Is there a utility that can format the
Javascipt so that it put each statement in a seperate line and indents
properly?
--
John Dalberg
Jul 23 '05 #1
9 5359
Ivo
"John Dalberg" <jo*****@hotmail.com> wrote
a hugely long stream of characters. Is there a utility that can format
the Javascipt so that it put each statement in a seperate line and
indents properly?


Different ideas what is proper indentation exist. I use this:
< http://4umi.com/web/bookmarklet/edit.htm >
It will also tell you if it finds an error.
hth
--
Ivo


Jul 23 '05 #2

"John Dalberg" <jo*****@hotmail.com> wrote in message
news:wr****************************@40tude.net...


I am using a utility that creates Javascript. However the javascript is one hugely long stream of characters. Is there a utility that can format the
Javascipt so that it put each statement in a seperate line and indents
properly?


See http://www.semdesigns.com/Products/F...Formatter.html

--
Ira D. Baxter, Ph.D., CTO 512-250-1018
Semantic Designs, Inc. www.semdesigns.com
Jul 23 '05 #3
"Ira Baxter" <id******@semdesigns.com> writes:
"John Dalberg" <jo*****@hotmail.com> wrote in message
news:wr****************************@40tude.net...

Is there a utility that can format the Javascipt so that it put
each statement in a seperate line and indents properly?


See http://www.semdesigns.com/Products/F...Formatter.html


Or let the browser do it:
---
<script type="text/javascript">
function reformat(code) {
try {
var func = Function("",code);
var text = func.toString();
var match = text.match(/function\s*\w*\(\)\s*\{([\s\S]*)}/);
if (match) {
return match[1];
} else {
return "ERROR\n" + code; //something wrong.
}
} catch (e) {
return "ERROR: " + e + "\n" + code;
}
}
</script>
<form action=""
onsubmit="this.elements['input'].value =
reformat(this.elements['input'].value);
return false;">
<textarea name="input" rows="10" cols="72">code here</textarea><br><input type="submit" value="Reformat">
</form>
---
Personally, I prefer the way Mozilla formats its Javascript :)
IE doesn't do any formatting at all, so don't use that.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
JRS: In article <br**********@hotpop.com>, dated Tue, 5 Apr 2005
20:44:00, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
var text = func.toString(); Personally, I prefer the way Mozilla formats its Javascript :)
IE doesn't do any formatting at all, so don't use that.


Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

I write my code (E&OE) to fit within 69-character-wide boxes (as seen in
IE 4), and I choose the height of each box to suit the code.

Are the results generally acceptable in other browsers, and could
anything be done to make the average better (given the wide use of IE)?

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
var text = func.toString();
Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

I write my code (E&OE) to fit within 69-character-wide boxes (as seen in
IE 4), and I choose the height of each box to suit the code.
Yes, checking in IE, I can see that the code doesn't have to overflow the
box :)
Are the results generally acceptable in other browsers, and could
anything be done to make the average better (given the wide use of IE)?


The boxes overflow in both Mozilla and Opera.

One of the problems is the number of empty lines between functions in
boxes with more than one function. In IE, there is one line, in both
Mozilla and Opera, there are three (an extra line before and after
each function). It shouldn't hurt to remove these empty lines, if they
exist.

Another difference is that IE doesn't reformat the body of the
function at all, whereas the other browsers do. In particular, they
move "}"'s to a line of their own. Opera also moves "{"'s to their
own line (the thing that makes me prefer Mozilla's format).
I don't see a simple solution to this.

The non-IE browsers also doesn't include comments in the output. All
in all, lines are probably shorter than in IE.

A non-simple solution would be to make the ShowFF function calculate
the necessary number of lines for the textarea, instead of providing
it as an argument. E.g.:

---
function trim(str) {
var match = /\S([\s\S]*\S)*/.exec(str);
return match ? match[0] : "";
}

function countLines(str, lineLength) {//counts lines when wrapped at lineLength
var lines = str.split(/[\n\r]/g);
var lineCount = lines.length;
for (var i = 0; i < lines.length; i++) {
lineCount += Math.floor(lines[i].length / lineLength);
}
return lineCount;
}

function ShowFF() { // Args are functions, last Arg is unused
var Len = arguments.length-1, S = ""
for (var j=0 ; j<Len ; j++) {
if (j>0) { S += "\n\n"; }
S += trim(arguments[j].toString());
}
var numLines = countLines(S, BoxX);
Depict(BoxX, numLines, S, "lightgreen") ; return "" }

function ShowDo(Fn, Ht) { // N.B. this calls Fn()
var string = trim(Fn.toString());
Depict(BoxX, countLines(string, BoxX), string, "red" ) ; Fn() ; return "" }

---

Good luck
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
JRS: In article <is**********@hotpop.com>, dated Thu, 7 Apr 2005
22:12:52, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
var text = func.toString();
Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

I write my code (E&OE) to fit within 69-character-wide boxes (as seen in
IE 4), and I choose the height of each box to suit the code.


Yes, checking in IE, I can see that the code doesn't have to overflow the
box :)
Are the results generally acceptable in other browsers, and could
anything be done to make the average better (given the wide use of IE)?


The boxes overflow in both Mozilla and Opera.
...
A non-simple solution would be to make the ShowFF function calculate
the necessary number of lines for the textarea, instead of providing
it as an argument. E.g.:
...


It's not quite that easy, since when I have

ShowFF(UsefulFunction(s), Demo(s)OfThatFunction, Length)

I often choose to make the box show only UsefulFunction(s) , with
Demo(s)OfThatFunction being visible to those who have noticed the thumb
on the vertical scroll-bar. You may not have seen the absence of the
thumb in cases without demo functions :-( .

Perhaps I'll make an empty parameter terminate size-counting.

Since I have 311 ShowFF and 122 ShowDo in 35 files, I think I'll use new
names and make the change slowly ...

Good luck


With code written by you, surely that is not needed?

Thanks.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7
JRS: In article <is**********@hotpop.com>, dated Thu, 7 Apr 2005
22:12:52, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
var lines = str.split(/[\n\r]/g);


In IE4, it appears that blank lines do not generate a corresponding
element in the array lines .

ISTR reading about varying behaviours of split().

Test page, showing old & new code in operation, is
<URL:http://www.merlyn.demon.co.uk/js-boxes.htm> .
Code should be self-documenting; but how to do a self-documenting blank
line ???

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #8
JRS: In article <Hn**************@merlyn.demon.co.uk>, dated Mon, 11 Apr 2005 23:34:23, seen in news:comp.lang.javascript, Dr John Stockton <sp**@merlyn.demon.co.uk> posted :
JRS: In article <is**********@hotpop.com>, dated Thu, 7 Apr 2005
22:12:52, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
var lines = str.split(/[\n\r]/g);
<URL:http://www.merlyn.demon.co.uk/js-boxes.htm> .

This, I think, does what countLines should have done :-
function LineCount(S, M) { // counts lines when wrapped at lineLength - blank lines ? A test blank line follows :-

var j = xj = R = N = 0, L = S.length, X = 1, C
while (j<L) { C = S.charCodeAt(j++)
if (C!=10 && C!=13) continue
if (C==10) N++
if (C==13) R++
X += Math.max(Math.floor((j-xj-2)/M), 0) ; xj = j }
// Not good enough, as MSIE splits at whitespace
return X + Math.max(N, R) }

// countLines = LineCount
Note that from "function" to ":-" is coded, posted, and transmitted
as a single line; how you see it depends on your choice of service,
software, and settings.

If the code is written so that coded line-length fits in box-size,
as I "always" do, then there is no need on my system to allow for
line-wrap. Is there then an actual need to consider line-wrap in
any other system? If there is, do other browsers wrap at exactly N,
rather than at the previous whitespace?

H'mmm - IE4 has a bug; although whitespace is reduced to newline
at such a wrap, the choice of wrap point is affected by the size
of the whitespace. However, that should only matter here if a
line is wrapped more than once.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
JRS: In article <is**********@hotpop.com>, dated Thu, 7 Apr 2005
22:12:52, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
var text = func.toString();
Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

Good luck


That worked.

Now I'm trying to improve the Pop-Up code display. It now puts a <pre>
rather than a <textarea> in the new window, and allows the window to
scroll. I also propose to incorporate auto-calculation of the "rows"
parameter, as in the Code Display section a little higher up the page.

It can be seen in the section Btn & PopCode which is just above
<URL:http://www.merlyn.demon.co.uk/js-nclds.htm#Inc3>.
Questions :

(A) In PopCode, the window height and width are somewhat pragmatical :-
var Wndw = window.open("", "X"+new Date().getTime(), // /scr-bar?
"height=" + (17*btn.btnargs[1]+28) + ",width=" + (8*BoxX+20) +
",resizable,scrollbars")
where btnargs[1] is the number of lines I want to show, BoxX the number
of characters per line I want to show, 20 and 28 give the right and
bottom margins matching the top and left ones, all empirical for my
present browser setup.

Without undue effort, can the initial height and width be set in due
proportion to the actual font size?
(B) In Btn, should document.close() be there (Btn is for execution
in-line during page display)? It's there as a result of possibly-
misinterpreted advice.
(C) Can SafeHTML be coded so that it is shown properly both in the page
proper and in the pop-up, and if so how? Its real code is
function SafeHTML(S) { // may be displayed incorrectly
return S.replace(/&/g, "&amp;").
replace(/</g, "&lt;").replace(/>/g, "&gt;") }

(D) Anything else?

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Alex Fitzpatrick | last post by:
Just by way of introduction, I'm currently the principal developer and maintainer of the a JavaScript editor plug-in for Eclipse. https://sourceforge.net/projects/jseditor/ The plug-in as it...
8
by: John Dalberg | last post by:
I have spent 1/2 hour looking for a Javascript formatter with no luck. I am using a tool that produces Javascript statements in one long string and it's hard to read. Any recommendations? I see...
4
by: Patrick De Ridder | last post by:
Which library should I include for the formatter in formatter.Serialize(output, record); Many thanks. -- Patrick De Ridder ngmail@freeler.nl
4
by: Andreas Huber | last post by:
Hello there I need to serialize/deserialize some pretty simple data structures (no inheritance, few has relationships, ~20 classes) in three formats. One is XML (structure is not important as...
4
by: Carlitos | last post by:
I have researched a lot trying to get this. So as a last resource I will have to ask here. What would be the equivalent to the following javascript excerpt: TheDataManager MyDMgr = new...
2
by: Nadav | last post by:
Hi, I am trying to create a custom formatter ( such as the binary formatter ), I can't figure out where do I bind the input Data Stream with the SerializationInfo object info how should i create...
1
by: Edward Yang | last post by:
When it comes to ViewState in ASP.NET, I have a mixed feeling of both love and hate. For love, it simplifies many aspects of common tasks; for hate, it bloats web pages with large amount of cryptic...
3
by: mistral | last post by:
I there any good javascript formatter tool? (format javascript accurately, etc) Mistral
6
by: Melih Onvural | last post by:
I need to execute some javascript and then read the value as part of a program that I am writing. I am currently doing something like this: import htmllib, urllib, formatter class...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.