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.
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.
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.
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.
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With