JavaScript Strings - Essential Guide to Handling Text in JavaScript
Discover how JavaScript strings, a fundamental data type, are used to manage textual content in web development. Enclosed in single quotes, double quotes, or backticks, strings in JavaScript offer flexibility and functionality for handling and manipulating text effectively. Learn the basics and examples of string literals in JavaScript.
JavaScript Strings
In JavaScript, a string is a primitive data type used for textual data. JavaScript strings can be enclosed in single quotes, double quotes, or backticks. Here are some examples of string literals:
String Literals
"Hello World"
'Hello World'
`Hello World`
A string literal can be assigned to a variable using the equal to =
operator:
String Variables
let str1 = "This is a double quoted string.";
let str2 = 'This is a single quoted string.';
let str3 = `This is a template string.`;
Template Strings
Template strings (using backticks) allow you to include variables or expressions within a string using ${variable}
syntax:
Template String Example
let amount = 1000, rate = 0.05, duration = 3;
let result = `Total Amount Payable: ${amount * (1 + rate * duration)}`;
Template strings can span multiple lines, unlike single or double quoted strings:
Multi-line Template String
let str1 = `This
is
multi-line
string`;
/ *let str2 = "This
will
give
error"; */
Strings as Character Arrays
You can treat strings like arrays to access individual characters using square brackets or the str.at(pos)
method:
Accessing Characters
let str = 'Hello World';
let ch1 = str[0]; // H
let ch2 = str[1]; // e
let ch3 = str.at(2); // l
let ch4 = str.at(3); // l
str[4] = "P"; // error
Using For Loops
Strings can be accessed using a for
loop:
For Loop Example
let str = 'Hello World';
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
for (let ch of str) {
console.log(ch);
}
Quotes Inside Strings
You can include quotes inside a string by using different types of quotes for the string:
Including Quotes in Strings
let str1 = "This is 'simple' string";
let str2 = 'This is "simple" string';
let str3 = `This is 'simple' and "easy" string`;
To include the same quotes as the surrounding quotes, use a backslash (\
):
Escaping Quotes
let str1 = "This is \"simple\" string";
let str2 = 'This is \'simple\' string';
String Concatenation
Strings can be concatenated using the +
operator or the concat()
method:
Concatenating Strings
let str1 = 'Hello ';
let str2 = "World ";
let str3 = str1 + str2; // Hello World
let str4 = str1.concat(str2); // Hello World
String Objects
JavaScript allows you to create a string object using the new
keyword:
Creating String Objects
let str1 = new String(); // create string object
str1 = 'Hello World'; // assign value
// or
let str2 = new String('Hello World'); // create and assign value
String objects and string literals are different. Use typeof()
to distinguish between them:
String Objects vs Literals
let str1 = new String('Hello World');
let str2 = "Hello World";
console.log(typeof(str1)); // "object"
console.log(typeof(str2)); // "string"
String Comparison
Strings can be compared using <
, >
, ==
, ===
operators, and the localeCompare()
method:
Comparing Strings
console.log("a" < "b"); // true
console.log("b" < "a"); // false
console.log("Apple" == "Apple"); // true
console.log("Apple" == "apple"); // false
console.log("Apple" === "Apple"); // true
console.log("Apple" === "apple"); // false
console.log("Apple".localeCompare("Apple")); // 0
console.log("Apple".localeCompare("apple")); // 1
Note that the ===
operator compares the reference of string objects, not their values:
String Object Comparison
let str1 = "Hello";
let str2 = 'Hello';
let str3 = new String('Hello');
console.log(str1 == str2); // true
console.log(str1 === str2); // true
console.log(str1 == str3); // true
console.log(str1 === str3); // false
String Methods & Properties
JavaScript strings have several properties and methods:
Property/Method | Description |
---|---|
length | Returns the length of the string. |
charAt(position) | Returns the character at the specified position (in Number). |
charCodeAt(position) | Returns a number indicating the Unicode value of the character at the given position (in Number). |
concat([string,,]) | Joins specified string literal values and returns a new string. |
indexOf(SearchString, Position) | Returns the index of the first occurrence of the specified String starting from the specified index. Returns -1 if not found. |
lastIndexOf(SearchString, Position) | Returns the last occurrence index of the specified SearchString, starting from the specified position. Returns -1 if not found. |
localeCompare(string) | Compares two strings in the current locale. |
match(RegExp) | Searches a string for a match using a specified regular expression. Returns a matching array. |
replace(searchValue, replaceValue) | Searches for a specified string value and replaces it with a specified replace value. Regular expressions can also be used as searchValue. |
search(RegExp) | Searches for a match based on a specified regular expression. |
slice(startNumber, endNumber) | Extracts a section of a string based on the specified starting and ending index and returns a new string. |
split(separatorString, limitNumber) | Splits a string into an array of strings by separating it based on a specified separator. Regular expressions can also be used as separators. |
substr(start, length) | Returns the characters in a string from the specified starting position through the specified number of characters (length). |
substring(start, end) | Returns the characters in a string between the start and end indexes. |
toLocaleLowerCase() | Converts a string to lowercase according to the current locale. |
toLocaleUpperCase() | Converts a string to uppercase according to the current locale. |
toLowerCase() | Returns the lowercase string value. |
toString() | Returns the value of a String object. |
toUpperCase() | Returns the uppercase string value. |
valueOf() | Returns the primitive value of the specified string object. |
String Methods for HTML
These string methods convert the string into an HTML wrapper element: