Ad space (banner)
🟨JavaScript Lessons
Lesson 9 / 69

Working with Strings

In this lesson you'll learn the representative methods for manipulating strings in JavaScript so you can freely process text data. This is for people searching "JavaScript string manipulation" or "JavaScript toUpperCase usage."

Strings come with a variety of methods. .toUpperCase() converts to uppercase, .slice(start, end) cuts out a portion, and .split(separator) splits by a separator into an array. String manipulation is one of the most frequently used features in real development, from handling user input to formatting what's shown on screen.

The sample code tries out uppercase conversion, getting character count with .length, extracting the first 5 characters with .slice(0, 5), and splitting with .split(", "), all on a string called message. These methods can also be chained together — for example, "trim the whitespace around an input string, then convert it to uppercase" can be written cleanly as one connected sequence.

A common beginner stumbling block is that .slice()'s end position means "up to, but not including, that index." .slice(0, 5) extracts the 5 characters from index 0 through index 4 — that gap in intuition trips people up, so be careful. Also remember that, unlike arrays, strings can't be modified directly (a new string is always returned instead), which helps avoid confusion.

In real development, string manipulation appears on nearly every screen of a web app — formatting a user's entered name or address for display, or splitting a search keyword to perform a filtered search. Combined with regular expressions (which you'll learn about later), even more advanced string processing becomes possible.

Combined with template literals (backtick strings), you can easily build messages with variable values embedded partway through a string. String methods come in many varieties, but if you firmly remember the four basics that appeared here, you'll be able to handle quite a lot of real-world situations.

.replace() lets you replace part of a string with another string. You pass the string or regular expression to replace as the first argument, and the replacement string as the second — a basic method often used for bulk text replacement too.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)