Javascript Equivalent to PHP Explode()

JavascriptPhpString

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

This is a direct conversion from your PHP code:

//Loading the variable
var mystr = '0000000020C90037:TEMP:data';

//Splitting it with : as the separator
var myarr = mystr.split(":");

//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];

// Show the resulting value
console.log(myvar);
// 'TEMP:data'

Solution 2 - Javascript

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']

Solution 3 - Javascript

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.

Solution 4 - Javascript

Looks like you want split

Solution 5 - Javascript

Try this:

arr = str.split (":");

Solution 6 - Javascript

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

Solution 7 - Javascript

Use String.split

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

Solution 8 - Javascript

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]; `

Solution 9 - Javascript

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)

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

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

Solution 14 - Javascript

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.

Solution 15 - Javascript

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/

Solution 16 - Javascript

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

Solution 17 - Javascript

try like this,

ans = str.split (":");

And you can use two parts of the string like,

ans[0] and ans[1]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDoug MolineuxView Question on Stackoverflow
Solution 1 - JavascriptJohn HartsockView Answer on Stackoverflow
Solution 2 - Javascriptpsycho brmView Answer on Stackoverflow
Solution 3 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 4 - JavascriptQuentinView Answer on Stackoverflow
Solution 5 - JavascriptweltraumpiratView Answer on Stackoverflow
Solution 6 - JavascriptJM DesignView Answer on Stackoverflow
Solution 7 - JavascriptGerman RummView Answer on Stackoverflow
Solution 8 - Javascripteriksv88View Answer on Stackoverflow
Solution 9 - JavascriptexebookView Answer on Stackoverflow
Solution 10 - Javascriptdylan maxeyView Answer on Stackoverflow
Solution 11 - JavascriptRuben KazumovView Answer on Stackoverflow
Solution 12 - JavascriptEfi NuhrView Answer on Stackoverflow
Solution 13 - JavascriptPharis KahamaView Answer on Stackoverflow
Solution 14 - JavascriptRamityView Answer on Stackoverflow
Solution 15 - Javascriptharish sharmaView Answer on Stackoverflow
Solution 16 - JavascriptAbdullahi Mako AyubaView Answer on Stackoverflow
Solution 17 - Javascriptmeignanamoorthy ksView Answer on Stackoverflow