JavaScript Strings
JavaScript Strings
A string in JavaScript is a sequence of characters use to represent text. Strings are one of the most commonly used data types because they allow us to display messages, store names, handle user input, and much more.
How to Create Strings in JavaScript
Strings can written inside:
-
Single quotes
' ' -
Double quotes
" " -
Backticks
(template literals)
Example:
String Length
You can use the .length property to find how many characters a string has.
Accessing Characters
You can access characters using:
-
Bracket notation
[] -
.charAt()
Common String Methods
JavaScript provides built-in methods to handle strings.
| Method | Description | Example |
|---|---|---|
toUpperCase() |
Converts string to uppercase | "hello".toUpperCase() → "HELLO" |
toLowerCase() |
Converts string to lowercase | "HELLO".toLowerCase()" → “hello” |
trim() |
Removes extra whitespace | " hi ".trim() → "hi" |
slice(start,end) |
Extracts part of a string | "JavaScript".slice(0,4) → "Java" |
replace(a,b) |
Replaces text | "I like JS".replace("JS","JavaScript") |
split() |
Splits a string into array | "a,b,c".split(",") → ["a","b","c"] |
String Concatenation (Joining Strings)
You can combine strings using:
-
+ -
+= -
Template literals
Template Literals (Modern Technique)
Template literals allow embedding variables using ${}.
Searching in Strings
| Method | Purpose |
|---|---|
indexOf() |
Returns position of substring (or -1 if not found) |
includes() |
Returns true/false if substring exists |
Escaping Characters
Some characters like quotes must be escaped with \.
Final Example
✔ Summary
-
Strings store textual data.
-
They can be created using
' '," ", or backticks`. -
JavaScript offers many useful methods to manipulate strings.
-
Template literals make string formatting easier.
