JavaScript Strings
Written by Avinash Malhotra
Updated on
What is a JavaScript string?
A JavaScript string is a primitive value that represents text. Strings are immutable. A method such as toUpperCase() returns a result and leaves the original text unchanged. See JavaScript data types for the other primitive types.
Use strings for names, email addresses and other text. The value property of an HTML input, select or textarea returns a string. For example, entering 42 in a number input gives "42" through value.
Single and double quotes create equivalent string literals. Open and close a literal with the same delimiter. For example, "hello" and 'hello' represent the same text.
A backslash, i.e., \, is used inside strings to escape characters. For example, var x="abc\"pqr";
Use const or let to give a string a name. Choose let if you plan to assign a different value later.
Declare Strings in JavaScript
const x="Tech Altum"; // string;
const y='Tech Altum'; // string;
const z=`Tech Altum`; // ES6 template literal
const str=String("abc"); // String() returns a primitive string
ECMAScript allows a string to contain up to 253 − 1 UTF-16 code units. JavaScript engines impose smaller practical limits.
Template Literals
A template literal uses backticks and can contain expressions and line breaks. ECMAScript 2015 (ES6) introduced this syntax.
let str=`js string`;
String Interpolation with Template Literals
To insert a value into a template literal, put an expression inside ${…}. JavaScript evaluates the expression and inserts its value as text. In the example below, both log statements print the same sentence.
const x=3;
const y=5;
console.log(`sum of ${x} and ${y} is ${x+y}`); //ES6
console.log("sum of " + x + " and " + y + " is " + (x+y)); //ES5
// Both statements print "sum of 3 and 5 is 8"
Multiline Strings
A line break inside a template literal becomes part of the string. With single or double quotes, you can include a newline escape (\n) and join the pieces with +.
let template=`<div>
this is div
</div>`;
String Properties
Read a string property using dot notation or brackets. For example, x.length and x["length"] read the same property.
String length
The length property counts UTF-16 code units. Each letter and space in "hello js" uses one unit. Each emoji in "😁😂" uses two, so the second string has a length of four.
8
let x="hello js";
x.length; // 8
4
let x="😁😂";
x.length; // 4
String length is read-only. In a non-strict script, JavaScript ignores the assignments below. In strict mode, attempting to assign to x.length throws a TypeError.
const x="hello js";
x.length; // 8
x.length=10;
x.length; // 8
x.length=2;
x.length; // 8
Empty String
An empty string contains no text and has a length of zero. A string containing one ordinary space has a length of one.
let x="";
x.length; // 0
String Methods
Call a string method by writing its name after a dot and putting any arguments in parentheses. Methods return different kinds of results. For example, trim() returns a string, while includes() returns a boolean.
Read text.length as a property. Call text.toUpperCase() as a method. The ECMAScript string method reference defines these operations.
at
at(index) returns a string containing the UTF-16 code unit at a zero-based index. A negative index counts back from the end, so at(-1) reads the last unit. An out-of-range index returns undefined.
const x="tech altum";
x.at(0) // return "t";
x.at(1) // return "e";
x.at(-1) // return "m";
indexOf
indexOf(text) returns the zero-based index of the first occurrence of the given text. The search is case-sensitive.
An unsuccessful search returns -1.
const x="tech altum";
x.indexOf("t") // return 0;
x.indexOf("e") // return 1;
x.indexOf("b") // return -1;
lastIndexOf
lastIndexOf(text) returns the zero-based index of the last occurrence of the given text. It is useful when a substring occurs more than once.
An unsuccessful search returns -1.
let x="tech altum";
x.indexOf("t") // return 0;
x.lastIndexOf("t") // return 7;
x.lastIndexOf("e") // return 1;
x.lastIndexOf("z") // return -1;
concat
concat() joins the original string and its arguments in order and returns the combined string.
let x="tech";
let y="altum";
x.concat(y); // return techaltum
The addition operator (+) can also join strings.
let x="tech";
let y="altum";
x+y; // return techaltum
charAt
charAt(index) returns the UTF-16 code unit at a zero-based index as a string. An out-of-range index returns an empty string.
let x="techaltum";
x.charAt(0); // return t
x.charAt(1); // return e
x.charAt(x.length-1); // return m
x.charAt(x.length); // return ""
charCodeAt
charCodeAt(index) returns the numeric value of one UTF-16 code unit. For ASCII characters this matches the ASCII code. To read the full Unicode code point of an emoji such as 😁, use codePointAt() at its starting index.
let x="techaltum";
x.charCodeAt(0); // return 116
x.charCodeAt(1); // return 101
toUpperCase
toUpperCase() returns the uppercase form of the string.
let x="techaltum";
x.toUpperCase(); // return "TECHALTUM"
To keep the result, assign it to a variable, for example const heading = x.toUpperCase().
toLowerCase
toLowerCase() returns the lowercase form of the string.
let x="Tech Altum";
x.toLowerCase(); // returns "tech altum"
substr
The legacy substr(start, length) method extracts up to the specified number of UTF-16 code units. Omitting the length extracts the rest of the string. You may see this method in older code. Use slice() for new code.
let x="techaltum";
x.substr(2); // return "chaltum"
x.substr(4); // return "altum"
x.substr(0,4); // return "tech"
x.substr(2,2); // return "ch"
x.substr(4,5); // return "altum"
substring
substring(start, end) extracts text from the start index up to the end index, excluding the end. Omitting the end extracts the rest of the string. Negative arguments become zero, and the method swaps the two indices if the start is greater than the end.
let x="techaltum";
x.substring(0,4); // return "tech"
x.substring(2,6); // return "chal"
x.substring(4); // return "altum"
slice
slice(start, end) includes the start and excludes the end. Negative indices count from the end. For example, "invoice.pdf".slice(-3) returns "pdf". If the resolved end comes before the start, the result is an empty string.
let x="techaltum";
x.slice(4); // "altum"
x.slice(0,4); // return "tech"
x.slice(-4); // return "ltum"
x.slice(2,-2); // return "chalt"
search
search(pattern) returns the index of the first regular expression match, or -1 if there is no match.
let x="tech altum";
x.search("t"); // return 0
x.search("T"); // return -1
x.search(/\s/);
// return 4, i.e, white space found at 4th index
x.search(/\d/);
// return -1, i.e, no digit found
Learn how to write patterns in the JavaScript regular expressions tutorial.
trim
trim() returns a string with whitespace removed from both ends. It preserves spaces between words.
let x=" tech altum ";
x.trim(); // return "tech altum"
trimStart()
trimStart() removes leading whitespace and preserves trailing whitespace.
let x=" tech altum ";
x.trimStart(); // return "tech altum "
trimEnd()
trimEnd() removes trailing whitespace and preserves leading whitespace.
let x=" tech altum ";
x.trimEnd(); // return " tech altum"
replace
With a string as its search pattern, replace() replaces the first match and returns the resulting string. A regular expression with the global flag (g) replaces every match.
let x="tech altum";
x.replace("t","T") // return "Tech altum"
x.replace("tech","TECH") // return "TECH altum"
x.replace(" ","-") // return "tech-altum"
Replace All Matches in a String
let x="tech altum";
x.replace(/t/,"T"); // returns "Tech altum"
x.replace(/t/g,"T"); // returns "Tech alTum"
replaceAll
replaceAll(search, replacement) replaces every occurrence of the search string. If you supply a regular expression, it must have the global flag (g).
let x="tech altum";
x.replace("t","T") // return "Tech altum"
x.replaceAll("t","T") // return "Tech alTum"
split
split(separator) divides a string at each separator and returns an array. With no argument, the array contains the entire string. An empty string separator splits the text into individual UTF-16 code units.
let x="tech altum";
x.split(""); // returns ["t","e","c","h"," ","a","l","t","u","m"]
x.split(" "); // return ["tech","altum"]
startsWith
startsWith(text) returns true if the string begins with the supplied text. The comparison is case-sensitive.
let x="tech altum";
console.log(x.startsWith("t")); // true
console.log(x.startsWith("T")); // false
console.log(x.startsWith("a")); // false
endsWith
endsWith(text) returns true if the string ends with the supplied text. For example, "report.pdf".endsWith(".pdf") returns true.
let x="tech altum";
console.log(x.endsWith("m")); // true
console.log(x.endsWith("t")); // false
includes
includes(text) returns true if the string contains the supplied text anywhere. Use indexOf() when you also need the position.
let x="tech altum";
console.log(x.includes("ch")); // true
console.log(x.includes("cm")); // false
Summary
Choose a string method according to the result you need. A search can give you a position or a boolean, an extraction gives you text, and splitting gives you an array.
- Accessing characters:
at(),charAt(),charCodeAt() - Finding substrings:
indexOf(),lastIndexOf(),search() - Modifying strings:
toUpperCase(),toLowerCase(),trim(),trimStart(),trimEnd(),replace(),replaceAll() - Extracting parts:
substr()(deprecated),substring(),slice(),split() - Checking contents:
startsWith(),endsWith(),includes() - Concatenation:
concat()method or+operator - Creating from codes:
String.fromCharCode()
For example, " New Delhi ".trim().toLowerCase() returns "new delhi". Each method uses the result of the previous call.
Create a String from an ASCII Code
String.fromCharCode() builds a string from one or more UTF-16 code unit values. ASCII codes are in this range, so String.fromCharCode(65) returns "A". For a Unicode code point above U+FFFF, use String.fromCodePoint().
String.fromCharCode(102); // return f
String.fromCharCode(65); // return A
To join strings, use the + operator or the concat() method.