Understanding String Literals in JavaScript

String literals in JavaScript allow for flexible ways to define text within your code, using single quotes, double quotes, or backticks. Each format offers different capabilities, especially backticks, which enable template literals for embedding expressions. Explore the basics with examples below to understand how to handle string literals in JavaScript effectively.



String Literals

JavaScript string literals can be enclosed in single quotes, double quotes, or backticks.

Example: String Literals

"Hello World"

'Hello World'

\`Hello World\`
            

String Variables

Strings can be assigned to variables using the = operator.

Example: 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 use backticks and can include variables and expressions using ${}. They can also span multiple lines.

Example: Template String

let amount = 1000, rate = 0.05, duration = 3;
let result = \`Total Amount Payable: ${amount * (1 + rate * duration)}\`;
            
Output

Total Amount Payable: 1157.625
            

Example: Multi-line Template String

Example: Multi-line Template String

let str1 = \`This 
            is
            multi-line 
            string\`;
            
Output

This 
            is
            multi-line 
            string
            

Strings as Arrays

Strings can be treated like arrays. Access characters using square brackets or the str.at(pos) method.

Example: String as Array

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 Loops with Strings

Strings can be accessed using a for loop or for...of loop.

Example: Use For Loops

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

Include single quotes in double-quoted strings or double quotes in single-quoted strings. Use a backslash to include the same quotes as the surrounding quotes.

Example: Quotes in Strings

let str1 = "This is 'simple' string";
let str2 = 'This is "simple" string';
let str3 = \`This is 'simple' and "easy" string\`;
            
Example: 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.

Example: String Concatenation

let str1 = 'Hello ';
let str2 = "World ";

let str3 = str1 + str2; // Hello World
let str4 = str1.concat(str2); // Hello World
            

String Objects

Strings can be created as objects using the new keyword. String objects differ from string literals.

Example: String Object

let str1 = new String(); // create string object
str1 = 'Hello World'; // assign value

// or

let str2 = new String('Hello World'); // create and assign value
            
Example: String Object vs Literal

let str1 = new String('Hello World');
let str2 = "Hello World";

console.log(typeof(str1)); // "object"
console.log(typeof(str2)); // "string"
            

Strings Comparison

Strings can be compared using mathematical operators, equality operators, and localeCompare() method.

Example: String Comparison

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
            

Example: String Object Comparison

Example: 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 various properties and methods for manipulation.

Property/Method Description
length Returns the length of the string.
charAt(position) Returns the character at the specified position.
charCodeAt(position) Returns the Unicode value of the character at the given position.
concat([string, ...]) Joins specified string literals and returns a new string.
indexOf(SearchString, Position) Returns the index of the first occurrence of the specified string.
lastIndexOf(SearchString, Position) Returns the last occurrence index of the specified string.
localeCompare(string, position) Compares two strings in the current locale.
match(RegExp) Searches a string for a match using a regular expression.
replace(searchValue, replaceValue) Searches for a string value and replaces it with another value.
search(RegExp) Searches for a match based on a regular expression.
slice(startNumber, endNumber) Extracts a section of a string and returns a new string.
split(separatorString, limitNumber) Splits a string into an array of substrings based on a separator.
substr(start, length) Returns characters from a string from a specified start position.
substring(start, end) Returns characters between specified start and end indexes.
toLocaleLowerCase() Converts a string to lower case according to the locale.
toLocaleUpperCase() Converts a string to upper case according to the locale.
toLowerCase() Returns the lower case version of the string.
toString() Returns the value of a string object.
toUpperCase() Returns the upper case version of the string.
valueOf() Returns the primitive value of a string object.

String Methods for HTML

The following methods convert strings into HTML wrapper elements.

Method Description
anchor() Creates an HTML <a> element around the string.
big() Wraps the string in a <big> tag.
blink() Wraps the string in a <blink> tag.
bold() Wraps the string in a <b> tag.
fixed() Wraps the string in a <tt> tag.
fontcolor() Wraps the string in a <font color="color"> tag.
fontsize() Wraps the string in a <font size="size"> tag.
italics() Wraps the string in a <i> tag.
link() Wraps the string in a <a> tag where the href attribute is set to the specified string.
small() Wraps the string in a <small> tag.
strike() Wraps the string in a <strike> tag.
sub() Wraps the string in a <sub> tag.
sup() Wraps the string in a <sup> tag.