Some notes on javascript strings

When using String.replace there are a few special characters matching regular expressions provide for using in the replacement string.

String.replace can use a function result as the replacement string:

	result = variable.replace(/\d(\d)(\w)/g, convert);

	function convert(matchedSubstring, Index, OriginalString) {
	   return 'x';
	 }

If a regular expression has back-references extra parameters are passed (in a very order)...

	function convert(matchedSubstring, ref1, ref2, Index, OriginalString) {
	   return 'x';
	}

Remember that replace can use a string for a simple match rather than construct a regular expression:

	result = variable.replace("apple", "fruit");

Functions

Passing arguments from one funtion to another:

	function second() {
		//arguments.length == 5
	}
   
	function first() {
		//arguments.length == 5
		second.apply(this, arguments);
	}
	
	first(1,2,3,4,5);

A quick method to convert the arguments array of a function to a real array with tandard methods available:

	var args = Array.prototype.slice.apply(arguments);

Recursion of anonymous functions

	var anonymous = function(n){
		if (n <= 1) {
			return 1;
		} else {
			return n*arguments.callee(n-1);
		}
	}

Arrays

Arrays are generally passed by reference (to functions or in assignment), to copy an array (or pass it by value):

	var newArray= oldArray.slice();

Array.concat() also creates a new array