1 convert the Javascript array to CSV format

Consider the application scenario where you have a Javscript character (or numeric) array that needs to be converted to a comma-separated CSV file. Then we can use the following tips, code is as follows:

12 var fruits = [``'apple'`` , ``'peaches'`` , ``'oranges'`` , ``'mangoes'``]; ``var str = fruits.valueOf();

Output: apple, peaches, oranges and mangoes

The valueOf() method converts a Javascript array to a comma-separated string. Note that if you do not want to use commas, such as | signs, use the join method as follows:

12 var fruits = [``'apple'`` , ``'peaches'`` , ``'oranges'`` , ``'mangoes'``]; ``var str = fruits.join(``"|"``);

Output: apple | peaches | oranges | mangoes

2 Convert the CSV format back to a Javscript array

So how do you convert a CSV string back into a Javascript array? We can use the split() method, which uses any of the specified characters to split, as follows:

12 var str = ``"apple, peaches, oranges, mangoes"``; ``var fruitsArray = str.split(``","``);

Output fruitsArray [0] : apple

3 Remove an element from the array based on the index

If you need to remove an element from a Javascript array, you can use the splice method, which removes the NTH element from the array (counting from bit 0 in Javascript arrays) based on the passed argument n.

1234567891011 function removeByIndex(arr, index) {`` ``arr.splice(index, 1); ``}`` test = ``new Array(); `` test[0] = ``'Apple'``; `` test[1] = ``'Ball'``; `` test[2] = ``'Cat'``; `` test[3] = ``'Dog'``; ``alert(``"Array before removing elements: "``+test); ``removeByIndex(test, 2); ``alert(``"Array after removing elements: "``+test);

The final output is Apple,Ball and Dog

4 Remove values from array elements based on their values

The following is a useful technique to remove an element from an array based on the given value:

1234567891011 function removeByValue(arr, val) {``    ``for``(``var i=0; i<arr.length; i++) {`` ``if``(arr[i] == val) {`` ``arr.splice(i, 1); `` ``break``; `` ``}`` ``}``}``var somearray = [``"mon"`` , ``"tue"`` , ``"wed"`` , ``"thur"``]`` removeByValue(somearray, ``"tue"``); '//somearray will have elements like "mon", "wed", "thur"

Of course, a better way to do this is to use prototype:

1234567891011 Array.prototype.removeByValue = ``function``(val) {``    ``for``(``var i=0; i<``this``.length; i++) {`` ``if``(``this``[i] == val) {`` ``this``.splice(i, 1); `` ``break``; ` ` ` `} ` ` ` `} ` `} ` `. / /. ``var somearray = [``"mon"`` , ``"tue"`` , ``"wed"`` , ``"thur"``]``somearray.removeByValue(``"tue"``);

5 Invoke a method dynamically in a string specified manner

Sometimes, at run time, you need to dynamically call an existing method and pass in arguments to it. How does that work? The following code can do this:

123456 var strFun = ``"someFunction"`` ; //someFunction is the name of the already defined method var strParam = ``"this is the parameter"`` ; // The argument to be passed to the method var fn = window[strFun]; // Fn (strParam);

6 Generate random numbers from 1 to N

1234567 var random = Math.floor(Math.random() * N + 1); // Generate a random number between 1 and 10 var random = Math.floor(Math.random() * 10 + 1); // Generate a random number between 1 and 100 var random = Math.floor(Math.random() * 100 + 1);

7 Capture the browser shutdown event

We often want to prompt the user to save something that hasn’t been saved when the user closes the browser, so this Javascript trick is very useful. It looks like this:

123456789 <script language=``"javascript"``>``function fnUnloadHandler() { ``alert(``"Unload event.. Do something to invalidate users session.." ` `); ` `} ` ` < / script > ` ` < body onbeforeunload = ` ` fnUnloadHandler "()" ` ` > ` `...... ``</body>

Just code the onbeforeUnload () event

8 Check whether the rollback button is pressed

Similarly, you can check if the user has pressed the back key as follows:

123 window.onbeforeunload = ``function``() {``    ``return "You work will be lost."``; ` `};

9 Check whether the form data has changed

Sometimes, you need to check if the user has changed the content of a form. You can use the following technique, which returns true if the content of the form has been changed and false if the content has not been changed. The code is as follows:

1234567891011121314151617181920212223242526272829303132333435363738 function formIsDirty(form) {``  ``for (``var i = 0; i < form.elements.length; i++) {``    ``var element = form.elements[i]; `` ``var type = element.type; `` ``if  (type == ``"checkbox"  || type == ``"radio"``) {``      ``if (element.checked ! = element.defaultChecked) {`` ``return true``; `` ``}`` ``}`` ``else if  (type == ``"hidden"  || type == ``"password" ||``             `` type == ``"text"  || type == ``"textarea"``) {``      ``if (element.value ! = element.defaultValue) {`` ``return true``; `` ``}`` ``}`` ``else if  (type == ``"select-one"  || type == ``"select-multiple"``) {``      ``for (``var j = 0; j < element.options.length; j++) {``        ``if (element.options[j].selected ! =`` ``element.options[j].defaultSelected) {`` ``return true``; `` ``}`` ``}`` ``}`` ``}`` ``return false``; ` `}  window.onbeforeunload = ``function``(e) {``  ``e = e || window.event; ``  ``if (formIsDirty (document. Forms [` ` "someForm ` `]]) {` ` ` ` / / Internet explorer and Firefox ` ` ` ` the if (e) {`` `` e.returnValue = ``"You have unsaved changes."``; `` ``}`` ``// Safari browser `` ``return "You have unsaved changes."``; ` ` ` `} ` `};

Do not use the back button completely

The following technique is used in a page to prevent users from hitting the back key, which is necessary in some cases. The code is as follows:

1234567 <SCRIPT type=``"text/javascript"``>`` ``window.history.forward(); `` ``function noBack() { window.history.forward(); }``</SCRIPT>``</HEAD>``<BODY onload=``"noBack();" `` ``onpageshow=``"if (event.persisted) noBack();" onunload=``""``>

11 Delete the items selected by the user

The following technique is used when the user selects multiple items in the drop-down box, and when clicking delete, can delete them at once. The code is as follows:

123456789101112131415161718192021 function selectBoxRemove(sourceID) {``   '// get the listbox id`` ``var src = document.getElementById(sourceID); ` ` // loop listbox`` ``for (' 'var count= src.options.length-1; count >= 0; count--) {``   ` ` / / if found to delete option, then delete ` ` ` ` if ` ` (SRC) options [count]. Selected = = ` ` true ` `) {` `                 ``try {`` `` src.remove(count, ``null``); ` `                  `` } ``catch``(error) {``                           ``src.remove(count); ` ` ` `} ` ` ` `} ` ` ` `} ` `}

12 Full and incomplete selection in Listbox

For a given listbox, the following method can be passed as true or false, depending on the user’s needs, to select all or not all items in the listbox:

123456 function listboxSelectDeselect(listID, isSelect) {``    ``var listbox = document.getElementById(listID); `` ``for``(``var count=0; count < listbox.options.length; count++) {`` ``listbox.options[count].selected = isSelect; ` ` ` `} ` `}

13 Move items up and down in the Listbox

The following code shows how to move items up and down in a listbox

123456789101112131415161718192021222324252627282930313233343536 function listbox_move(listID, direction) {``       ``var listbox = document.getElementById(listID); `` ``var selIndex = listbox.selectedIndex; ` ` ``if``(-1 == selIndex) {`` ``alert(``"Please select an option to move."``); `` ``return``; ` ` ` `} ` `     ``var increment = -1; `` ``if`` (direction == ``'up'``)`` ``increment = -1; `` ``else`` ``increment = 1; ` ` ``if``((selIndex + increment) < 0 ||`` ``(selIndex + increment) > (listbox.options.length-1)) {`` ``return``; ` ` ` `} ` `     ``var selValue = listbox.options[selIndex].value; `` ``var selText = listbox.options[selIndex].text; `` ``listbox.options[selIndex].value = listbox.options[selIndex + increment].value`` ``listbox.options[selIndex].text = listbox.options[selIndex + increment].text`` ``listbox.options[selIndex + increment].value = selValue; `` ``listbox.options[selIndex + increment].text = selText; ` ` ``listbox.selectedIndex = selIndex + increment; ` `} ` ` / /.. ` ` / /.. ` ` listbox_move(``'countryList'`` , ``'up'`` ); ``//move up the selected option``listbox_move(``'countryList'`` , ``'down'`` ); ``//move down the selected option

14 Move items between two different Listboxes

If you are in two different listboxes and often need to move items from one of the left listboxes to the other, here is the code:

123456789101112131415161718192021222324252627 function listbox_moveacross(sourceID, destID) {``    ``var src = document.getElementById(sourceID); `` ``var dest = document.getElementById(destID); ` `     ``for``(``var count=0; count < src.options.length; count++) {``           ``if`` (src.options[count].selected == ``true``) {``                ``var option = src.options[count]; ` `                 ``var newOption = document.createElement(``"option"``); `` ``newOption.value = option.value; `` ``newOption.text = option.text; `` `` newOption.selected = ``true``; `` ``try {`` `` dest.add(newOption, ``null`` ); ``//Standard`` `` src.remove(count, ``null``); `` ``}``catch``(error) {`` `` dest.add(newOption); ``// IE only`` ``src.remove(count); `` ``}`` ``count--; ` ` ` `} ` ` ` `} ` `} ` `. / /. ` ` / /.. ``listbox_moveacross(``'countryList'`` , ``'selectedCountryList'``);

15 Quickly initialize Javscript arrays

The following method gives a quick way to initialize a Javscript array:

123 var numbers = []; ``for``(``var i=1; numbers.push(i++)<100;) ; //numbers = [0,1,2,3... 100]

We use the array push method

16 Intercepts the decimal number of specified digits

If you want to intercept a specified number of digits after a decimal, you can use the toFixed method, as in:

12 Var num = 2.443242342; ``alert(num.toFixed(2));

Using toPrecision(x) provides the precision of the specified number of bits, where x is the total number of bits, as in:

12 Num = 500.2349; `` result = num.toPrecision(4); 500.2 ` ` / / output

17 Check whether the string contains other characters

In the following code, it is possible to check whether a string contains other strings. The code is as follows:

1234567891011121314 if (! Array.prototype.indexOf) {`` `` Array.prototype.indexOf = ``function``(obj, start) {`` ``for (``var  i = (start || 0), j = ``this``.length; i < j; i++) {``             ``if (``this`` [i] === obj) { ``return i; }``         ``}``         ``return - 1; ` ` ` `} ` `} ` ` if (! String.prototype.contains) {`` `` String.prototype.contains = ``function (arg) {``        ``return !!!!! ~``this``.indexOf(arg); ` ` ` `}; ` `}

The above code overrides the indexOf method and defines the CONTAINS method, using the following methods:

123 var hay = ``"a quick brown fox jumps over lazy dog"``; ``var needle = ``"jumps"``; ``alert(hay.contains(needle));

Remove duplicate elements from Javscript arrays

The following code can remove duplicate elements from a Javascript array:

123456789101112131415 function removeDuplicates(arr) {``    ``var temp = {}; `` ``for (``var i = 0; i < arr.length; i++)`` `` temp[arr[i]] = ``true``; ` `     ``var r = []; `` ``for (``var  k ``in temp)`` ``r.push(k); `` ``return r; ` `} / / usage ` ` var fruits = [``'apple'`` , ``'orange'`` , ``'peach'`` , ``'apple'`` , ``'strawberry'`` , ``'orange'``]; ``var uniquefruits = removeDuplicates(fruits); '// output uniquefruits ['apple', 'orange', 'peach', 'strawberry'];

19 Remove extra Spaces from String

The following code adds a trim() method to String as follows:

12345678910 if (! String.prototype.trim) {`` ``String.prototype.trim=``function``() {`` ``return this`` .replace(/^\s+|\s+$/g, ``''``); ` ` ` `}; ` `} ` ` / / usage ` ` var str = ``" some string "``; ``str.trim(); '// output STR = "some string"

20 Redirection in Javascript

In Javascript, redirection can be implemented as follows:

1 window.location.href = <a href=``"http://viralpatel.net"``>http://viralpatel.net</a>;

21 Encode the URL

Sometimes, you need to encode the pass in the URL as follows:

12 var myOtherUrl =``       ``"http://example.com/index.html?url=" + encodeURIComponent(myUrl);