String
The string is one of the basic data types in JavaScript. It is simply some characters inside quotes. The characters can be letters, numbers, punctuation, or any other symbol that you can type.
It's common to specify strings using:
- Single quotes
- Double quotes
String examples:
"Hello!" // a string in double quotes
'1234' // a string consists of numbers in single quotes
"" // an empty string
Quotation marks inside strings
Both single and double quotation marks can be used to indicate the beginning and the end of a string. If you use single quotes, then the string itself can contain double quotes, or vice versa:
let s = 'Hello, "world"!`
let t = "I'll be back soon.";
Another solution is to use the backslash escape character (\
). This character has special meaning when used inside a string. Now you can insert a single quote character inside a string enclosed by a pair of single quotation marks:
let t = 'I\'ll be back soon.';
When the single quote character follows \
, it means a character inside the string instead of the end of the string.
Working with Strings
Concatenation
"Concatenate" is a fancy programming word that means "join together". To joining strings together, use the plus (+
) operator:
console.log("Hello, " + "world") // Hello, world
toLowerCase/toUpperCase
toLowerCase()
creates a new string by converting all characters in a string to lower case, while toUpperCase()
converts to upper case:
let s = "Hello"
console.log( s.toUpperCase() ) // HELLO
replace()
You can replace one substring inside a string with another substring using the replace()
method. The returned text is a new string.
let str = "Hello, World!";
let str1 = str.replace('World','Everybody');
console.log(str1); // Hello, Everybody!
console.log(str); // Hello, World! (original str unchanged)