When you split("d") in the program, are we not suppose to have 4? Why 3? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

When you split("d") in the program, are we not suppose to have 4? Why 3?

var arr = "donald".split("d") document.write(arr.length)

14th Jul 2019, 12:59 PM
eMBee
eMBee - avatar
11 Answers
+ 6
"donald".split("d") = "|d|onal|d|" = "", "onal", ""
14th Jul 2019, 2:04 PM
Seb TheS
Seb TheS - avatar
+ 6
Hmm Dhanush Adithya, thanks
14th Jul 2019, 3:59 PM
eMBee
eMBee - avatar
+ 5
Thank you guys for answers Dhanush Adithya and ODLNT but still, you guys haven't explained why the output of the code is 3
14th Jul 2019, 2:07 PM
eMBee
eMBee - avatar
+ 5
If you cut the string "donald" from 2 points: "" 🔪 "onal" 🔪 "" The length is 3, because also empty strings will be separated. I somehow understand how you got 4, but I can not explain it. I can only say, that if you cut a string 2 times, result will be 3 strings.
14th Jul 2019, 2:15 PM
Seb TheS
Seb TheS - avatar
+ 4
Oh I see @Seb TheS
14th Jul 2019, 2:10 PM
eMBee
eMBee - avatar
+ 4
d onald d -> 1 2 3 😉
14th Jul 2019, 3:00 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 3
Mofey var arr = "donald".split("d").join("") document.write(arr.length) Output : 4
14th Jul 2019, 1:27 PM
deeyae
deeyae - avatar
+ 2
Mofey, Add this to your snippet - document.write("<br/>"+JSON.stringify(arr)); It will answer your question.
14th Jul 2019, 1:30 PM
ODLNT
ODLNT - avatar
+ 2
Mofey Like Seb TheS said if you split the it'll be separated and it'll store the separate stings in an object When you use the .length it'll display the object's length as 3 After using join() the empty strings is joined to the original string So it again becomes a string after using join() and the output will be 4 By the way , it's an nice question
14th Jul 2019, 2:34 PM
deeyae
deeyae - avatar
0
Can anyone suggest some good c++ project ideas
14th Jul 2019, 7:58 PM
Siddharth Sid
Siddharth Sid - avatar