Welcome! In this lesson, we'll delve into the basic string manipulation features of JavaScript, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.
In JavaScript, we can use the split
method from the String
class to tokenize a string, essentially splitting it into smaller parts or 'tokens'.
We start by declaring a string variable sentence
containing the text "JavaScript is an amazing language!". On the second line, we use the split
method with a space character " "
as the delimiter. This method splits the sentence
every time it encounters a space and returns an array of substrings or tokens. In this case, the resulting tokens
array will contain ["JavaScript", "is", "an", "amazing", "language!"]. We then use the forEach
method to iterate over each element (token) in the tokens
array. The arrow function token => console.log(token)
is executed for each token, printing each word to the console, one per line.
In JavaScript, the +
operator or template literals can be used to concatenate strings into a larger string:
Using the +
Operator:
Using Template Literals:
You can also concatenate arrays of strings in JavaScript using the join
method:
Using Array join
Method:
In the example above:
- Array Initialization: We initialize an array with several strings.
- Using the
join
Method: We use thejoin
method to concatenate all the elements of the array into a single string. Thejoin
method can also take an optional delimiter as an argument if you need to insert characters (like commas or spaces) between the elements.
In JavaScript, the trim
method can remove both leading and trailing whitespace from a string:
In this example, trim
is used to remove leading and trailing whitespace from a string.
We can convert strings to numbers using methods like parseInt
(string to integer) and parseFloat
(string to float), and other data types to strings using String
:
In this code, we use parseInt
, parseFloat
, and String
for type conversions.
In some cases, we may need to combine all the methods discussed:
By integrating these methods, we can transform the string 1,2,3,4,6
into an array of integers, calculate their average, and display the result.
Great job! You've gained an overview of JavaScript's string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, and type conversions. Now, it's time to get hands-on with these concepts in the exercises that follow. Happy coding!
