Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split and get first and last occurrences

Tags:

javascript

I have a long string of ISO dates:

var str = "'2012-11-10T00:00:00.000Z', '2012-11-11T00:00:00.000Z', ****  '2013-11-12T00:00:00.000Z'";

I need to get the first and last dates only. I could do

var vStr = str.split(',');
vStr[0] and vStr[vStr.length - 1]

But it's a waste memory, because I only need the first and last occurrences. Ideas? Thanks.

like image 584
Daviddd Avatar asked Dec 10 '13 14:12

Daviddd


People also ask

How do you split a string and get the last element?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

Does split () alter the original string?

Note: The split() method does not change the original string. Remember – JavaScript strings are immutable. The split method divides a string into a set of substrings, maintaining the substrings in the same order in which they appear in the original string. The method returns the substrings in the form of an array.


2 Answers

If you're really getting a performance problem from the large array (dont' optimize prematurely), you could use slice to extract the single strings and indexOf/lastIndexOf to find their positions:

str.slice(0, str.indexOf(','))
and
str.slice(str.lastIndexOf(',')+1) // 1==','.length
like image 167
Bergi Avatar answered Oct 14 '22 10:10

Bergi


It's really not a waste of space, since Javascript is barely taking up any memory on the computer. Unless the string is gigabytes long, I wouldn't worry about it. To get the first and last, just do this:

arr=str.split(',');
var first=arr.shift(); //or arr[arr.length-1];
var last=arr.pop(); //or arr[0];
like image 41
scrblnrd3 Avatar answered Oct 14 '22 12:10

scrblnrd3