473,788 Members | 3,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5379
Ivo
"John Dalberg" <jo*****@hotmai l.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*****@hotmai l.com> wrote in message
news:wr******** *************** *****@40tude.ne t...


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******@semde signs.com> writes:
"John Dalberg" <jo*****@hotmai l.com> wrote in message
news:wr******** *************** *****@40tude.ne t...

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("",cod e);
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.e lements['input'].value);
return false;">
<textarea name="input" rows="10" cols="72">code here</textarea><br><i nput 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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
JRS: In article <br**********@h otpop.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.toStri ng(); 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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5
Dr John Stockton <sp**@merlyn.de mon.co.uk> writes:
var text = func.toString() ;
Code display within my javascript pages is largely based on
function.toStri ng(); 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(line s[i].length / lineLength);
}
return lineCount;
}

function ShowFF() { // Args are functions, last Arg is unused
var Len = arguments.lengt h-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.toStrin g());
Depict(BoxX, countLines(stri ng, BoxX), string, "red" ) ; Fn() ; return "" }

---

Good luck
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
JRS: In article <is**********@h otpop.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.de mon.co.uk> writes:
var text = func.toString() ;
Code display within my javascript pages is largely based on
function.toStri ng(); 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(UsefulFu nction(s), Demo(s)OfThatFu nction, Length)

I often choose to make the box show only UsefulFunction( s) , with
Demo(s)OfThatFu nction 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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7
JRS: In article <is**********@h otpop.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.demo n.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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.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.de mon.co.uk> posted :
JRS: In article <is**********@h otpop.com>, dated Thu, 7 Apr 2005
22:12:52, seen in news:comp.lang. javascript, Lasse Reichstein Nielsen
<lr*@hotpop.co m> posted :
var lines = str.split(/[\n\r]/g);
<URL:http://www.merlyn.demo n.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.f loor((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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
JRS: In article <is**********@h otpop.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.de mon.co.uk> writes:
var text = func.toString() ;
Code display within my javascript pages is largely based on
function.toStri ng(); 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.demo n.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,scr ollbars")
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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.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
2018
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 stands supports syntax highlighting and outlining of functions, classes and their methods.] When I took over the project in June it was for the purpose of adding outlining facilities for JavaScript written in an OO style with classes and so on. I...
8
1957
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 a .NET tool at codeproject but that site is down.
4
5980
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
7817
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 long as it's human-readable and modifiable), and two are proprietary binary formats. For XML I'll use the SoapFormatter, no sweat. For the two other formats I would like to implement my own formatters. Problem is the docs on implementing your own...
4
2183
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 TheDataManager(); File MyDataFile = new File(strDataPath); // Create a new file if and only if it doesn't already exist
2
2178
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 the association? I couldn't find any sample explaining how to create custom formatters... Any pointer or sample would be appreciated... -- Nadav http://www.ddevel.com
1
2907
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 (though not really :-)) text. I find that LOS formatter is not as effecient as what Microsoft claims. It takes up much of CPU time. For example, it is very obvious in CPU utilization (up to 50% for one page) when serializing/deseriailzing a...
3
3373
by: mistral | last post by:
I there any good javascript formatter tool? (format javascript accurately, etc) Mistral
6
3577
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 myparser(htmllib.HTMLParser): insave = 0 def start_div(self, attrs): for i in attrs: if i == "id" and i == "pr":
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.