Removal of New Line Break and Tab/Indentation in JavaScript

Here is the best possible coding for removal of newline break and tab/indentation:

; for (var i=0; i‹ txt.length; i++) txt = txt.replace('\n', ' ')
; for (var i=0; i‹ txt.length; i++) txt = txt.replace('\t', ' ')

This approach avoids the possible non-working of method .search() and RegExp. For details please refer to http://koncordpartners.blogspot.com/2010/02/deal-with-literals-and-escape-sequences.html

Deal with Literals and Escape Sequences in JavaScript

Literals are special characters for which their original meaning, as a character, had been replaced by their processing software. The processing software used these characters to flag something else. In JavaScript, literals are:

. | * ? + ( ) { } [ ] ^ $ \

As a result, if one wants to deal with these literals, one would find s/he will not be able to process them normally. At lease, escape “\” would be needed to replace in front of the literal.

Escape sequences are actually aliases for single characters which do have special meaning. For instance, \n is the alias of a character with code number 0x0A, which means a newline in text. In comparison with literals, it even has worse situation because normal work processing, such as Windows Notepad, does not even show them.
In JavaScript, it is so strange JavaScript does not even have an integrated policy to deal with them. Following are examples:

Literal Asterisk, or *

For method .search(), neither .search(‘*’) nor .search(‘\*’) world work in many browsers.
For method .replace(), .replace(‘*’, newPattern) does not work. However, .replace(‘\*’ , newPattern) does work.
For method .replace(RegExp), neither .replace(new RegExp(‘*’, flag), newPattern) nor .replace(new RegExp(‘\*’, flag), newPattern) works.

Escape Sequence Newline, or \n

For method .search(), none of .search(‘\n’), .search(‘\\n’) or .search(‘\\\n’) world work.
For method .replace(), .replace(‘‘\n’’, newPattern) does work. However, .replace(‘\\n’ , newPattern) or .replace(‘\\\n’ , newPattern) does not work.
For method .replace(RegExp), .replace(new RegExp(‘\n’, flag), newPattern) does work but .replace(new RegExp(‘\\n’, flag), newPattern) and .replace(new RegExp(‘\\\n’, flag), newPattern) does not work.

As a conclusion:

1. Escape sequence, such as \n is just a presentation. Rather, it is INDEED a single character. Any attempt to place an escape ‘\’ in front of it means a failure. The correct usage is just ‘\n’.

2. Method .search() does not work at all. Forget this method at all if you are not sure if your text contains literals, or if you want your function to process escape sequences.

3. Do deal with literals, the best approach is to replace them with another non-literal character or a string first before the dealt. Sure, the best approach to replace them is to use method .replace() without the utilization of Regular Expression. Since .replace() can only deal with the first occurrence of the matching, one would need to do it recursively or by loop.

4. For escape sequences, the best approach is the same as that for literals, by replacing them with a non- escape sequence character or a string first. Surprisingly, /n and /t does not behave same with RegExp, though they are same escape sequences.

5. Universally, following coding might be the best approach for replacing both literals and escape sequences:

; for (var i=0; i‹ textContent.length; i++) textContent = textContent.replace('\*', newPattern)

or

; for (var i=0; i‹ textContent.length; i++) textContent = textContent.replace('\t', newPattern)

The JavaScript RegExp Object

RegExp provides a vehicle for other JavaScript methods to conduct a batch process. For instance .replace(“oldSubStr”, “newSubStr”) would only replace the first matching pattern. By using RegExp, it can be archived for all matching patterns: .replace(new RegExp(“oldSubStr”, “flag”), “newSubStr”), or simply .replace(/oldSubStr/flag, “newSubStr”). Three flags g, i, m can be used as parameter for search: Global Search, Ignore Case and Multiline Input.

There are two problems with RegExp, however.

1. The simple way of RegExp can’t deal with string reference, such as .replace(/oldSubStr/flag, “newSubStr”). oldSubStr must be a string, not the string reference.

2. If your text, as a string data type, contains following literals, it won’t work properly:

. | * ? + ( ) { } [ ] ^ $ \

It is thought when escape sign \ added it would work. Unfortunately, in reality, it usually won’t work. It is therefore suggested when those literals exist in your text, you should write your own recursive or loop function to process it. Here is an example:

; var len = textContent.length
; for (var i=0; i‹len; i++) textContent = textContent.replace('\*', pattern)

http://www.w3schools.com/jsref/jsref_obj_regexp.asp
http://www.araxis.com/merge/topic_regexpreference.html
http://www.regular-expressions.info/reference.html
http://www.evolt.org/regexp_in_javascript

Koncord Code Cleanser

We have officially deployed an online code optimizer located at: http://koncord.webs.com/.

The code optimizer can compress your website codes as well as remove comments on codes, which supposed to be used by the programmers.

Please use Firefox since IE won’t work properly.

Click here to go there: http://koncord.webs.com/

Following is the Terms of Services of Koncord Partners: http://koncordpartners.blogspot.com/2010/06/terms-of-services.html

HTML Page Loading Sequence

HTML page loading sequence is to load head first, then body, then window.onload event. If one use document.write() to write DHTML and for which the value is to be assigned by window.onload event, it will be failed because HTML body would be loaded before window.onload event. That is why in DHTML, document. getElementById().innerHTML is preferred in comparison to document.write().

When HTML head being loaded, sequentially it loads external JavaScript files. If more than one JS files exist, be careful the sequence; because for functions have not loaded yet, but called by window.onload, an error will occur.

Use getElementById().innerHTML in DHTML

In comparison with document.write(), document. getElementById().innerHTML is very useful because it can be changed after load. However, it cannot be used to insert a row in the table. To do it, it is suggested to insert a complete inner table. Yes, frame your row by an inner table within the table.

A New Sorting Mechanism in Database

If one wants to add a field to record sorting order, following mechanism is recommended.

In HTML’s Select List or Option List, the positioning indication can be written as:

Before Item 1 – Order_Value is 0
Before Item 2 – Order_Value is 1

Then, the Sort_Order can be written into Database as Order_Value*2-1, which can be applied in both cases as new record or move existing record. By doing this, one can easily insert or move item. This is because in database this field is recorded as 0, 2, 4, 6... Of course, inserting or moving can be done once a time, followed by sorting.

Following is the example in PHP.

public function saveCateNew($order)
{ $orderNew = $order*2-1;
$query = sprintf( ' INSERT INTO CATES_SELF '
. ' (TITLE_1 '
. ' , SORT_ORDER '
. ' ) VALUES '
. ' ("%s" '
. ' , %d '
. ' ) '
, mysql_real_escape_string($this->title_1, $GLOBALS['DB'])
, $orderNew
);
mysql_query($query, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$this->sortCate();
}

public function saveCateOld($order)
{ $orderNew = $order*2-1;
$query = sprintf( ' UPDATE CATES_SELF '
. ' SET TITLE_1 = "%s" '
. ' , SORT_ORDER = %d '
. ' WHERE ID_CATESELF = %d '
, mysql_real_escape_string($this->title_1, $GLOBALS['DB'])
, $orderNew
, $this->id_cateself
);
mysql_query($query, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$this->sortCate();
}

function sortCate()
{ $query = sprintf( ' SELECT ID_CATESELF '
. ' FROM CATES_SELF '
. ' ORDER BY SORT_ORDER '
);
$result = mysql_query($query, $GLOBALS['DB']);
$index = 0;
while($row = mysql_fetch_assoc($result))
{ $id = $row['ID_CATESELF'];
$queryInner = sprintf( ' UPDATE CATES_SELF '
. ' SET SORT_ORDER = %d '
. ' WHERE ID_CATESELF = %d '
, $index
, $id
);
mysql_query($queryInner, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$index = $index+2;
};
mysql_free_result($result);
}

Option List in HTML

Code in HTML:

‹form id="oForm" name="oForm" action="" method="POST"›
‹select id="sList" name="sList" onchange="picking(this.form.cateList)"›
‹/select›
‹/form›

Script in JavaScript:

; var position
; var len

; window.onload = function()
{ ; len = selfCate.length
; for (var i=0; i ; createOption('cateForm', 'cateList', len, 'At the end')
; document.cateForm.cateList[len].selected = true
; position = len
}

; function picking(dropDown)
{ ; var myIndex = dropDown.selectedIndex
; position = dropDown.options[myIndex].value
}

; function createOption(formName, selectName, indexValue, newText)
{ ; var objSelect = document.forms[formName].elements[selectName]
; var objOption = document.createElement("option")
; objOption.value = indexValue
; objOption.text = newText
; if(document.all && !(window.opera)) objSelect.add(objOption)
else objSelect.add(objOption, null)
}

; function removeOptions(selectId, firstNumToKeep, lastNumTokeep)
{ ; var elSel = document.getElementById(selectId)
; var total = elSel.length - lastNumTokeep - 1
; for (var i=total; i>=firstNumToKeep; i--) elSel.remove(i)
}

Special Notes:

1. In window.onload, “document.cateForm.cateList[len].selected = true” is to show what item is preselected in HTML. It is “position = len” to tell PHP what was preselected, if preselected has not been changed.

2. In picking(), apart of the need of global variable, the writing of var position = dropDown.options[myIndex].value is not recommended because some browser request variable declaration and assignment being separated.

Multiple Forms in HTML

If there are more than one form in HTML, give every input item a global unique id and name. Else, PHP won’t be able to pick up right item, although you might put input item in right order in HTML.

Labels