JavaScript Function urldecode, in_array, implode and explode

JavaScript Function urldecode, in_array, implode and explode

In this post, we will be making JavaScript  functions such as

  • urldecode
  • in_array
  • implode
  • explode

urldecode

function urldecode (str) {
return decodeURIComponent(str.replace(/+/g, ' '))
}

in_array

in_array equivalent function in JavaScript 1.6 Array.indexOf , but it is not supported in older browsers.

function in_array(needle, haystack) {
  var key = '';
    for (key in haystack) {
      if (haystack[key] == needle) {
        return true;
      }
    }
  return false;
}

Input/Output

var haystack=new Array(1,2,3,4);
alert(in_array('4', haystack));

implode

function implode(glue, pieces) {
    var i = '',
    returnVal = '',
    tmpGlue = '';
  if (arguments.length === 1) {
    pieces = glue;
    glue = '';
  }
  if (typeof pieces === 'object') {
    if (Object.prototype.toString.call(pieces) === '[object Array]') {
      return pieces.join(glue);
    }
    for (i in pieces) {
      returnVal += tmpGlue + pieces[i];
      tmpGlue = glue;
    }
    return returnVal;
  }
  return pieces;
}

Input/Output

var pieces=new Array(1,2,3,4);
alert(implode('-', pieces));

explode

function explode(delimiter, string, limit) {
  if (typeof delimiter === 'undefined' || typeof string === 'undefined') return null;
  if (delimiter === '' || delimiter === false || delimiter === null) return false;
  if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string ===
    'object') {
    return {
      0: ''
    };
  }
  if (delimiter === true) delimiter = '1'; 
  delimiter += '';
  string += ''; 
  var s = string.split(delimiter); 
  if (typeof limit === 'undefined') return s; 
  if (limit === 0) limit = 1;

  //  Positive
  if (limit > 0) {
    if (limit >= s.length) return s;
    return s.slice(0, limit - 1)
      .concat([s.slice(limit - 1)
        .join(delimiter)
      ]);
  }

  //  Negative
  if (-limit >= s.length) return [];

  s.splice(s.length + limit);
  return s;
}

Input/Output

alert(explode(',', "1,2,3,456"));
 alert(explode(',',"a,b,c,cde"));

Leave a Reply

Top