21 Javascript tips to collect

  • 2020-03-30 01:35:10
  • OfStack

1   Javascript array converted to CSV format

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

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

Output: apple, peaches, oranges and mangoes

Where the valueOf() method converts the Javascript array into a comma-separated string. Note that if you don't want to use a comma split, such as a | split, use the join method, as follows:

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

Output: apple | peaches | oranges | mangoes

2. Convert the CSV format back to the Javscript array

So how do you convert a string in CSV format back into a Javascript array? You can use the split() method to separate with any specified character. The code is as follows:

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

Output fruitsArray [0] : apple

Removes an element from an array by 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 based on the parameter n passed in.

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 last output is Apple,Ball and Dog

Remove the value from the array element based on the value of the element

The following trick is very practical. It is to delete the elements in the array according to the given value. The code is as follows:

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

Of course, a better way is to implement it using prototype's methods, as follows:

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

Call a method dynamically in a way specified by the string

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

var strFun = "someFunction"; //SomeFunction is the defined method name
var strParam = "this is the parameter"; //The parameter to pass in to the method
var fn = window[strFun];

//The calling method passes in parameters

6 generates random Numbers from 1 to N

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

Capture the browser closing event

<script language="javascript">
function fnUnloadHandler() {

       alert("Unload event.. Do something to invalidate users session.."); 
<body onbeforeunload="fnUnloadHandler()">

Just write the code for the onbeforeunload() event

8   Check if the back button is pressed

Again, you can check whether the user has pressed the back key, and the code is as follows:

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

9   Check if the form data has changed

Sometimes, when you need to check whether the user has changed the contents of a form, you can use the following technique, which returns true if you have changed the contents of the form, or false if you have not changed the contents of the form. The code is as follows:

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
    if (e) {
      e.returnValue = "You have unsaved changes.";
    return "You have unsaved changes.";

10   Do not use the back button at all

The following tips are placed on the page to prevent the user from clicking the back button, which is required in some cases. The code is as follows:

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

Deletes the items selected in the user's checkbox

The following tips are as follows: when the user selects multiple items in the drop-down box, they can be deleted at one time when they click delete. The code is as follows:

function selectBoxRemove(sourceID) {   
    //Get the id of the listbox
    var src = document.getElementById(sourceID);

    //Loop listbox
    for(var count= src.options.length-1; count >= 0; count--) {

         //If the option to delete is found, delete
        if(src.options[count].selected == true) {

                try {
                         src.remove(count, null);

                 } catch(error) {


12   Select all and select not all in the Listbox

If for the specified listbox, the following method can pass in true or false according to the needs of the user, indicating whether all items in the listbox are selected or not, the code is as follows:

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

Move items up and down in the Listbox

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

function listbox_move(listID, direction) {

    var listbox = document.getElementById(listID);
    var selIndex = listbox.selectedIndex;

    if(-1 == selIndex) {
        alert("Please select an option to move.");

    var increment = -1;
    if(direction == 'up')
        increment = -1;
        increment = 1;

    if((selIndex + increment) < 0 ||
        (selIndex + increment) > (listbox.options.length-1)) {

    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

Move items in two different listboxes

If you are in two different listboxes, it is often necessary to move items in one Listbox on the left to another Listbox, the following is the relevant code:

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
listbox_moveacross('countryList', 'selectedCountryList');

15 quickly initializes a Javscript array

The following method, gives a quick method to initialize the Javscript array, the code is as follows:

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

It USES the push method of the array

Intercepts a decimal number of specified digits

If you want to intercept the specified number after the decimal, you can use the toFixed method, such as:

var num = 2.443242342; 

ToPrecision (x) is used to provide the precision of the specified number, where x is all the digits, such as:

num = 500.2349; 
result = num.toPrecision(4); //The output of 500.2

Check for other strings in the string

In the following code, you can check whether a string contains other strings. The code is as follows:

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);

In the code above, the indexOf method is rewritten and the contains method is defined, using the following method:

var hay = "a quick brown fox jumps over lazy dog"; 
var needle = "jumps"; 

18   Remove duplicate elements from the Javscript array

The following code can remove duplicate elements in the Javascript array, as follows:

function removeDuplicates(arr) {
    var temp = {};
    for (var i = 0; i < arr.length; i++)
        temp[arr[i]] = true;

    var r = [];
    for (var k in temp)
    return r;

// usage 
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//Output uniquefruits [' apple ', 'orange', 'peach', 'strawberry'].

19   Remove the extra Spaces in the String

The following code will add a trim() method to the String as follows:

if (!String.prototype.trim) {
   String.prototype.trim=function() {
    return this.replace(/^s+|s+$/g, '');

// usage 
var str = "  some string    ";
//Output STR = "some string"

20 redirection in Javascript

In Javascript, redirection can be implemented as follows:

window.location.href = "//www.jb51.net";

21 encode the URL

Sometimes, it is necessary to encode the transmission in the URL. The method is as follows:

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

Original: http://viralpatel.net/blogs/javascript-tips-tricks/

Related articles: