Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split() js last array item

I am newbie to web development and JS in particular.

I am using a String object method split on this string:

let str = 'Look at me '; //last character is space
console.log(str.split(' '));

The separator for split is ' ' as well space. I expect to have an array of 3 items as well as I understan how split works. However, I got this:

['Look', 'at', 'me', '']

Can somebody explain please to me why does this happen? Thanks in advance!

like image 465
lessismore Avatar asked May 19 '26 16:05

lessismore


2 Answers

ECMA-262 specifies how split() is implemented in JavaScript.

It's quite hard to read, but here's my stab at interpreting it…

Step 14 specifies that the split() always ends by grabbing the slice up to where the string ends:

  1. Let T be a String value equal to the substring of S consisting of the characters at positions p (inclusive) through s (exclusive).

That slice is then added to the array of outputs:

  1. Call the [[DefineOwnProperty]] internal method of A with arguments ToString(lengthA), Property Descriptor {[[Value]]: T, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false.

Remember that split()'s argument is a delimiter (also known as a separator).

"ABC".split("B") treats "B" as a delimiter, delimiting the substrings "A" and "C".

"ABC".split("C") treats "C" as a delimiter, delimiting the substrings "AB" and "". Yes, empty string is still a string, and thus "C" separates the substring "AB" from the substring "".

Your example is the same, except instead of "C", you have a space character, " ". Space is not special in any way, so the same rule applies: it separates the preceding substring from the substring after it (which happens to be empty).

like image 55
Birchlabs Avatar answered May 22 '26 04:05

Birchlabs


The split() function effectively divides a string into pieces and puts those pieces into an array. The first parameter to the function (' ') is an empty space, meaning that the division happens wherever there is a blank space. Your string, 'Look at me ' has three spaces in it, or three divisions. If you were to take a long piece of cake and cut it three times, you would end up with four pieces. In the real world, you of course wouldn't have a fourth piece that is effectively "empty" or blank, but in computer science, you just get an extra piece that doesn't have anything in it.

The solution, as noted by @ppasler is to trim any excess whitespace from the string you're attempting to split. trim() removes whitespace from the beginning and end of a string, meaning that trim('Look at me ') would result in 'Look at me'. If you then use split on that resulting string, you will get: ['Look', 'at', 'me'].

like image 43
Chris Rasys Avatar answered May 22 '26 04:05

Chris Rasys