Moving Between Text and Arrays
Introduction
Welcome to Storing and Updating Lists with JavaScript Arrays. We’ve learned to read, update, and reshape array values; now we’ll connect arrays with text. We’ll use split() to turn text into an array and join() to turn an array back into text. We’ll also trace what type each method returns, see what happens when separators repeat, and revise one array value before creating new text from it. By the end, we’ll be able to move between a written route and an editable list of stops.
Splitting Text into an Array with split()
A route written as "Depot|Museum|Park" is one string, even though it names three stops. To work with each stop separately, we can split the string wherever a chosen separator appears. The separator is written as a string, so "|" tells JavaScript to look for the literal vertical bar. The code snippets below continue one program in order.
This program splits the route at each vertical bar and prints the resulting array. The output shows one array value for each stop.
split() returns a new array of strings. Here, stops holds one value for each section of route, while route itself remains unchanged. This gives us a list we can read or revise using the array positions we learned about earlier.
What Comes Back: Types and Positions
The two values have different types: route is a string, and stops is an array. We can use the same zero-based indexing we used with strings, but now each position contains a stop name rather than a character. Position 1 is the second stop.
This program reads the value at position 1 from the split array. The output shows Museum, the second stop.
The split result is an array, so stops[1] reads its second value, "Museum". The position tells us which item we get; it does not change the array. As with other array lookups, position counting begins at 0.
Joining an Array into Text with join()
To turn an array back into text, we call join() with the separator we want between its values. The separator can differ from the one used by split(). For example, the original route uses vertical bars, but we can join its stops using an arrow surrounded by spaces. Before joining, we replace the middle array value using the position assignment from earlier lessons.
This program replaces the middle stop, joins the array with an arrow separator, and prints the new text alongside the original route. The output shows that only the joined text changed.
join() returns a string, not an array. It places " -> " between each value in stops; it does not add that separator before the first value or after the last one. The call to join() leaves the updated array unchanged and stores the new text in updatedRoute. The original string still contains "Museum": editing the array does not rewrite route.
