Académique Documents
Professionnel Documents
Culture Documents
I've found this mind blowing function for padding a string in JavaScript:
Parameters of the function stand for: l=maximal length of the string, s=padding string and
t=type of padding (0=left, 1=right and 2=center).
A logical OR expression is evaluated until a member is true, therefore the expression s || (s=" ")
actually means: if s contains something then it is true and left alone, otherwise s will contain
exactly one space.
Expression (l-=this.length) makes l contain the number of needed characters for the string to
have the required length (if the length of the string is 7 and we want it padded to 20 characters,
now the l is 13).
If new l is greater than 0, then computations are required, otherwise the string (referenced
using this) is returned as it is.
Math.ceil(<value>) gives the closest upper integer value of the given value.
1
join(<separator>) creates a single string value from the array it is applied to using the given
separator string.
Finally, if something left to be added is added at the end, using substr again. For left padding
(t=0) there is nothing left to be added because t=l=13 and l-t=0, resulting in
"{}{}{}{}{}{}{xunrage". For right padding t=1, we have t=0 initially (t==1 ? 0 : ...) and l-t=13 at the
end, resulting in "xunrage{}{}{}{}{}{}{". For center padding t=2 and we have t=Math.ceil(l/2)
which is t=Math.ceil(13/2)=Math.ceil(6.5)=7, finally l-t=13-7=6, resulting in "{}{}{}{xunrage{}{}{}".
Now you can see how amazing this one line of code is.
2
Functions in JavaScript
A Delphi programmer like me, accustomed with strongly typed programming, with clear
function block limitation and with classic object oriented style, finds JavaScript overwhelmingly
weird. In JavaScript a variable type is interpreted and can happily jump from one type to
another, object oriented is based on prototyping starting from the Object primitive type and
functions are objects derived from Object.
The Object type has two properties (constructor, prototype) and six methods (eval, toSource,
toString, unwatch, valueOf, watch) (see http://docs.sun.com/source/816-6408-10/object.htm).
Function is a type descended from Object and has six more properties (arguments,
arguments.callee, arguments.caller, arguments.length, arity, length) and two methods (apply,
call) (see http://docs.sun.com/source/816-6408-10/function.htm).
or
var myObject = { }
In the second notation, the members of the object are expressed like name:value pairs as:
function myType(a,b,c){
this.a=a;
this.b=b;
this.c=c;
}
3
Then you can use this object like:
function myType(a,b){
this.a=a;
this.b=b;
this.add = function(){ with(this) return a+b; }
}
f = new myType(5,6);
document.write(f.add()); // The result is 11
Note that the add method is present in any object created and if there are 1000 instances of
myType, there are also 1000 instances of the function add. To avoid this, use the prototype
keyword like this:
function myType(a,b){
this.a=a;
this.b=b;
}
myType.prototype.add = function(){ return this.a + this.b; }
f = new myType(19,11);
document.write(f.add()); // The result is 30
There can be created a helper function like:
function myType(a,b){
this.a=a;
this.b=b;
}
4
Add a new method like this:
To continue a string on the next line in JavaScript, use the \ operator like this:
function functionAssembler(operatorSign){
return new Function("a","b","return a" + operatorSign + "b;");
}
Use it to create functions:
document.write(add(10,5));
document.write(substract(12,6));
document.write(multiply(5,3));
document.write(divide(125,5));
5
Detecting Internet Explorer version with Javascript
I have found on the Internet the following function for detecting Internet Explorer version:
The property navigator.userAgent returns something like: Opera/9.80 (Windows NT 6.1; U; en)
Presto/2.6.30 Version/10.63
The function returns the conditional result of the expression <logical> ? <value_for_true> :
<value_for_false>
Constructor RegExp creates a new object and defines a regular expression as: [0-9] defines a
character set formed by any character in the range 0-9; {x,} defines the minimum x number of
occurrences used in the match; () creates a sub expression.
RegExp.exec(string) returns an array of the matches of the regular expression in the given string
or null if no match is found. The returned array contains both matches for the regular
expression as well as for present sub expressions. For this reason, the second element in the
array is parsed to a float value and returned by the function.
6
if(vIE()<0){
document.write("N/A");}
else{
if(isIE8()){
document.write("8");
if(vIE()==7) document.write(" (Compatibility View)");
}
else{ document.write(vIE()); }
}
</script>
if(navigator.javaEnabled()){ ... }
function myfunction(){
var myvariable=19.21;
this.mymethod = function(){ return myvariable; };
this.increase = function(amount){ myvariable+=amount; };
}
var f = new myfunction();
document.write("initial value is " + f.mymethod());
f.increase(0.80);
document.write("<br/>new value is " + f.mymethod());
Because the function myfunction is used as a class for the object f, the local variable myvariable
is considered private and it can be accessed only by member functions like mymethod and
increase.
7
Javascript object functions runs on creation
Consider the code bellow:
function myfunction(){
document.write("I was executed.");
}
var f = new myfunction();
The function myfunction is used as a class for the object f, and is also executed at creation time.
function escapeltgt(s){
s=s.replace(lt,"&"+"lt;");
s=s.replace(gt,"&"+"gt;");
return s;
}
Naming conventions
When someone like me puts a lot of markup and javascript inside posts there is always a risk to
create conflicting ids and names. One solution is to create a naming convention. Therefore a
good idea will be to create master functions (or classes if you like) that contain all the javascript
code, and the markup to be inserted using javascript also. The class function will have a name
like xunClass_12345678, the instance of the class the name like xunInstance_12345678, while
markup elements something like xun[Markup]_12345678_1234, where 12345678 is a unique
alphanumeric id for the class and is identical for the instance and any markup, while for markup
the last 1234 is a unique id in that area. See the source code for this post for an example.
Markup:
9
And this is how it is done:
var lt=String.fromCharCode(0x003c);
var gt=String.fromCharCode(0x003e);
var quot=String.fromCharCode(0x022);
function replaceall(s,matchString,replaceString){
var olds = s;
s = olds.replace(matchString,replaceString);
while(s!=olds){
olds = s;
s = olds.replace(matchString,replaceString);
}
return s;
}
function escapeltgtquot(s){
s = replaceall(s,lt,"&"+"lt;");
s = replaceall(s,gt,"&"+"gt;");
s = replaceall(s,quot,"&"+"quot;");
return s;
}
function putquotes(s){
return replaceall(s,"^",quot);
}
var e = document.getElementById(divid);
e.innerHTML=br+"hello from " + divid;
}
var xunInstance_f9s6k7x1 = new xunClass_f9s6k7x1();
</script>
10
Child Div
Below is a div with the border dashed and using javascript a new div is added as its child.
Internet Explorer is a bit different from Firefox and the others when it comes to this DOM
action. I took style information from
http://msdn.microsoft.com/en-us/library/ms535240(VS.85).aspx.
The code:
11