393

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?

0

17 Answers 17

661

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'
Sign up to request clarification or add additional context in comments.

10 Comments

it should be noted that the array starts at [0]
@Herr Kaleun... That is understood... But OP wanted the last two items in the array.
+1: That's correct; here's a link from MDN: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…. And the "opposite" direction, so the PHP implode() equivalent is myArray.join(':'): developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
NOTE: split(delimiter,limit)'s limit parameter does NOT work the same as explode($delimiter,$string,$limit)'s limit parameter. Example: explode('.','1.2.3.4',3) === array('1','2','3.4') - while in Javascript, you'll get: '1.2.3.4'.split('.',3) === ['1', '2', '3']. Anyone know how to easily replicate PHP's method?
I've added a code comments to clear up the array[0] stuff, could be confusing the newbies...
|
55
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']

2 Comments

Kudos for being the ONLY one, as far as I can see, to provide an ACTUAL equivalent to PHP's explode functionality (as per the original question).
What a simple and elegant solution, I wish this was the accepted response.
48

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.

2 Comments

Someone probably thought you were being snarky. Sometimes you have to explain everything. Eg, "Your problem is best solved by 'indexOf' ...but 'split' answers your question literally."
Downvoter: "How dare you provide a simpler and more performant solution instead of validating my preconceptions??"
32

Looks like you want split

Comments

10

Try this:

arr = str.split (":");

Comments

7

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

1 Comment

Seems a little overkill, ty for the response tho
6

Use String.split

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

Comments

5

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

5 Comments

I wanted to look at her, but only got messy JavaScript in front of me. Uhm, emptyArray = { 0: '' }? :-/
I have not said that it is the best solution, but it is a good solution if you're new to JavScript and is familiar with php. But there was a reason why I wrote another example. :) "Keep it simple stupid!";)
That sounds reasonable, but I think one shouldn't want to transform one programming language in another; that could be misleading to newbie's who might think that OOP in JavaScript is like OOP in C++. Moreover, someone might simply copy-pasted the linked function and think that one has to define arrays that way.
Yes, completely agree there! But it's not really getting the code into his hand. and that's it. If he knows php, so maybe he misses little things in php. It is best logic I am referring to the logic, not as a copy pastels solution, there is never a good solution! My experience is that the day of realizes that it has a lot to learn, that's when you are on the right track.
+1 As far as I can see this is the only solution which functions the same as PHP. If the delimiter is not found the result is the original string explode('foo','bar'); // 'bar' This is the reason I arrived here and for my purposes a copy and paste script which I intend to use with limits is absolutely perfect. I don't have to get sidelined into creating my own. Why reinvent the wheel after all, k.i.s.s.
4

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)

1 Comment

This answer should have 554 upvotes, not the accepted answer. Also, for the past 3 years the accepted answer has been completely wrong, concatenating indices 0 and 1 when the OP asked for 1 and 2.
2

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

Comments

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

1 Comment

Very witty answer. I wonder how well it performs compared to a traditional split.
1

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

Comments

1

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

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

Comments

0

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.

Comments

0
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

1 Comment

This does not even work! splice accepts 2 digits and strings as parameters, not a ~ (this causes a syntax error). And splice is not for this purpose, it's to get/take out items from or add to an array.
0

try like this,

ans = str.split (":");

And you can use two parts of the string like,

ans[0] and ans[1]

1 Comment

Perhaps explain how this differs from the accepted answer posted 8 years ago.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.