[javascript] Javascript Equivalent to PHP Explode()

I have this string:

0000000020C90037:TEMP:data

I need this string:

TEMP:data.

With PHP I would do this:

$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];

How do I effectively explode a string in JavaScript the way it works in PHP?

This question is related to javascript php string

The answer is


var str = '0000000020C90037:TEMP:data';    // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, "");          // str = "TEMP:data"

Just a little addition to psycho brm´s answer (his version doesn't work in IE<=8). This code is cross-browser compatible:

function explode (s, separator, limit)
{
    var arr = s.split(separator);
    if (limit) {
        arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
    }
    return arr;
}

create's an object :

// create a data object to store the information below.
    var data   = new Object();
// this could be a suffix of a url string. 
    var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated 
// by the & character as a combined string, in addition it passes up the ? mark
    var pairs = string.substring(string.indexOf('?')+1).split('&');
    for(var key in pairs)
    {
        var value = pairs[key].split("=");
        data[value[0]] = value[1];
    }

// creates this object 
    var data = {"id":"5", "first":"John", "last":"Doe"};

// you can then access the data like this
    data.id    = "5";
    data.first = "John";
    data.last  = "Doe";

try like this,

ans = str.split (":");

And you can use two parts of the string like,

ans[0] and ans[1]


You don't need to split. You can use indexOf and substr:

str = str.substr(str.indexOf(':')+1);

But the equivalent to explode would be split.


Looks like you want split


console.log(('0000000020C90037:TEMP:data').split(":").slice(1).join(':'))

outputs: TEMP:data

  • .split() will disassemble a string into parts
  • .join() reassembles the array back to a string
  • when you want the array without it's first item, use .slice(1)

var str = "helloword~this~is~me";
var exploded = str.splice(~);

the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get


String.prototype.explode = function (separator, limit)
{
    const array = this.split(separator);
    if (limit !== undefined && array.length >= limit)
    {
        array.push(array.splice(limit - 1).join(separator));
    }
    return array;
};

Should mimic PHP's explode() function exactly.

'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']

With no intentions to critique John Hartsock, just in case the number of delimiters may vary for anyone using the given code, I would formally suggest to use this instead...

var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var arrlen = myarr.length;
var myvar = myarr[arrlen-2] + ":" + myarr[arrlen-1];

Try this:

arr = str.split (":");

I used slice, split and join You can just write one line of code

      let arrys = (str.split(":").slice(1)).join(":");

So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:

function explode(str,begin,end)
{
   t=str.split(begin);
   t=t[1].split(end);
   return t[0];
}

This function works well if you are trying to get the values between two values. For instance:

data='[value]insertdataherethatyouwanttoget[/value]';

If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.

out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget

But let's say you don't have those handy "tags" like the example above displayed. No matter.

out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou

Wana see it in action? Click here.


If you want to defined your own function, try this:

function explode (delimiter, string, limit) {
  if (arguments.length < 2 ||
    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'
  }

  // Here we go...
  delimiter += ''
  string += ''

  var s = string.split(delimiter)

  if (typeof limit === 'undefined') return s

  // Support for limit
  if (limit === 0) limit = 1

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

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

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

Taken from: http://locutus.io/php/strings/explode/


Use String.split

"0000000020C90037:TEMP:data".split(':')


If you like php, take a look at php.JS - JavaScript explode

Or in normal JavaScript functionality: `

var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript