The following statement is inaccurate in regards to JavaScript (under-the-hood differences from other languages), but is still relevant:
Basically, strings can be looked at as arrays of chars, that have been manipulated (in a similar way to how split() and join() do, as shown in an example hereinafter).
Because of said manipulation, many array methods won't work on strings - although there are some alternatives.
Let there be string:
const str = 'abcde';
Here's an alternative to using array methods on strings, for example:
const char = str[3];
//=> d
chars can be accessed this way similarly to elements of an array
The above would have normally been: char = str.charAt(3))
, but we can use index positioning to find our char.
Lets try another array method on our string:
const reversedString = str.reverse();
//=>TypeError: str.reverse is not a function
Whoops!! This threw an error! str is not an array...
Lets try a different approach:
const arrStr = str.split('');
//=> [ 'a', 'b', 'c', 'd', 'e' ]
As you can see, we used the split() method to convert the string into an array.
This can also be achieved like this: const arrStr = [...str];
(using the spread operator).
Now lets use array methods on an array! Let's try reverse() again:
const revArrStr = arrStr.reverse();
//=> [ 'e', 'd', 'c', 'b', 'a' ]
Not this time, Error!
We need our string to be a string again:
const revStr = revArrStr.join('');
//=> 'edcba'
Now that's the stuff!
So we can use the split() method to convert a string into an array - use array methods on it - and then join() it back together.
In other words: We can operate on strings in their "array version", as arrays.
But there are a lot of wasted chars all over this page.
Lets shorthand it all:
const shortRevStr = str.split('').reverse().join('');
//=> LOG: edcba
Short and sweet!
Other methods that work on arrays, but not on strings can be used on these 'temporary' arrays as well.
The ability to manipulate strings in this way, allows us access to many additional tools.
I'd love to hear about some of the ways that you use data type manipulation to your advantage!
Top comments (0)