Working with Strings in JavaScript

This chapter delves into the world of strings in JavaScript, providing a thorough explanation from the ground up to advanced concepts. We'll explore how to create, manipulate, and extract information from strings, all presented in clear language with illustrative examples. Buckle up and get ready to master strings in JavaScript!

Introduction: What are Strings?

In JavaScript, strings are sequences of characters used to represent text. They can hold anything from simple words to complex sentences, code snippets, or even emojis. Strings are essential for building user interfaces, processing data, and interacting with the web.

Creating Strings:

There are three main ways to create strings in JavaScript:

1 Single Quotes (”):

				
					let name = 'Alice';

				
			

2 Double Quotes (“):

				
					let message = "Hello, world!";

				
			

3 Template Literals (“): (Introduced in ES6) Template literals offer additional features like string interpolation (embedding variables within strings):

				
					let greeting = `Welcome, ${name}!`;

				
			

String Methods Table

CategoryMethodDescription
Extracting CharacterscharAt(index)Returns the character at the specified index.
charCodeAt(index)Returns the Unicode character code at the specified index.
substring(start, end)Extracts a part of the string from a start index to an end index (end not included).
slice(start, end)Similar to substring but can accept negative indexes.
substr(start, length) (deprecated)Extracts a part of the string from a start index with a specified length.
Searching & ReplacingindexOf(substring, fromIndex)Returns the first index at which a substring is found.
lastIndexOf(substring, fromIndex)Returns the last index at which a substring is found.
search(regexp)Searches for a regular expression in the string.
replace(regexp/substr, replacement)Replaces a part of the string with a new string.
replaceAll(regexp/substr, replacement)Replaces all occurrences of a substring with a new string (not supported in all browsers).
Case ConversiontoUpperCase()Converts the string to uppercase.
toLowerCase()Converts the string to lowercase.
Checking & Modifyingconcat(string1, string2, ...)Concatenates strings.
trim()Removes whitespace from the beginning and end of the string.
trimStart()Removes whitespace from the beginning of the string.
trimEnd()Removes whitespace from the end of the string.
startsWith(searchString, position)Checks if the string starts with a specified substring.
endsWith(searchString, position)Checks if the string ends with a specified substring.
includes(searchString, position)Checks if the string includes a specified substring.
padStart(targetLength, padString)Pads the beginning of the string to a specified length with another string.
padEnd(targetLength, padString)Pads the end of the string to a specified length with another string.
repeat(count)Repeats the string a specified number of times.
Splitting & Joiningsplit(separator, limit)Splits a string into an array of substrings based on a specified separator.
join(separator)Joins array elements into a string, separated by a specified separator.
Getting InformationlengthReturns the length of the string.
localeCompare(compareString)Compares two strings based on the current locale.

Getting Information:

While strings behave like primitive values, JavaScript provides properties and methods to work with them.

length:

 This property returns the number of characters in a string, including spaces.

				
					let message = "JavaScript";
console.log(message.length); // Output: 10

				
			

localeCompare(compareString)

The localeCompare() method in JavaScript is used to compare two strings in a locale-sensitive manner. It returns a number indicating whether the reference string comes before, after, or is the same as the compare string in sort order.

The method returns:

  • A negative number if the string comes before the compareString.
  • Zero if the string and the compareString are equivalent.
  • A positive number if the string comes after the compareString.
				
					const str1 = 'apple';
const str2 = 'banana';

console.log(str1.localeCompare(str2)); // Output: -1
console.log(str2.localeCompare(str1)); // Output: 1
console.log(str1.localeCompare(str1)); // Output: 0

				
			

Extracting Substrings

You can access individual characters within a string using their zero-based index. The first character has an index of 0, the second has an index of 1, and so on.

charAt(index):

 This method returns the character at the specified index.

				
					let word = "Hello";
console.log(word.charAt(0)); // Output: "H"
console.log(word.charAt(4)); // Output: "o" (index 4 points to the last character)

				
			

Note: If you try to access an index outside the string’s length, it will return an empty string (“”).

charCodeAt()

The charCodeAt() method in JavaScript returns the Unicode value of the character at a specified index within a string. Unicode is a universal character encoding standard that assigns a unique number (code point) to each character in most of the world’s writing systems.

				
					let str = "Hello";
let unicodeValue = str.charCodeAt(1); // Returns the Unicode value of the character 'e' at index 1
console.log(unicodeValue); // Output: 101

				
			

There are several methods to extract substrings (portions of a string) in JavaScript:

slice(start, end):

 This method extracts a section of the string and returns a new string.

				
					let str = "JavaScript for Everyone";
let subStr = str.slice(0, 10); // From index 0 (inclusive) to 9 (exclusive)
console.log(subStr); // Output: "JavaScript"

				
			

substring(start, end):

 Similar to slice, but it allows negative indices to start from the end of the string.

				
					let str = "Hello, World!";
let subStr = str.substring(7); // From index 7 (inclusive) to the end
console.log(subStr); // Output: "World!"

				
			

substr(start, length):

 This method (considered less flexible) extracts a substring of a certain length starting from a specified index.

				
					let str = "JavaScript";
let subStr = str.substr(4, 4); // Start at index 4, extract 4 characters
console.log(subStr); // Output: "Scri"

				
			

substring(start, end):

 Similar to slice, but it allows negative indices to start from the end of the string.

Remember: These methods create new strings; they don’t modify the original string.

String Searching and Replacement

indexOf(searchValue, fromIndex):

 This method searches for a substring within the string and returns the index of its first occurrence. If not found, it returns -1.

				
					let str = "Welcome to JavaScript";
let index = str.indexOf("JavaScript");
console.log(index); // Output: 11

				
			

lastIndexOf(substring, fromIndex):

This method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.

				
					const str = 'hello world';

console.log(str.lastIndexOf('o')); // Output: 7
console.log(str.lastIndexOf('o', 5)); // Output: 4
console.log(str.lastIndexOf('z')); // Output: -1

				
			

search(regexp):

This method searches a string for a specified value or regular expression. If a match is found, search returns the index of the match; otherwise, it returns -1.

				
					const str = 'hello world';

console.log(str.search(/o/)); // Output: 4
console.log(str.search(/z/)); // Output: -1

				
			

replace(regexp/substr, replacement):

This method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a regular expression.

				
					const str = 'hello world';

console.log(str.replace('world', 'universe')); // Output: hello universe
console.log(str.replace(/o/g, '0')); // Output: hell0 w0rld

				
			

replaceAll(regexp/substr, replacement)

 This method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a regular expression.

				
					const str = 'hello world';

console.log(str.replaceAll('o', '0')); // Output: hell0 w0rld
console.log(str.replaceAll(/l/g, '1')); // Output: he11o wor1d

				
			

Case Conversion:

toUpperCase():

This method converts all the characters in a string to uppercase letters

				
					const str = 'hello world';

const upperCaseStr = str.toUpperCase();

console.log(upperCaseStr); // Output: HELLO WORLD

				
			

In this example, the toUpperCase() method is called on the string 'hello world', which converts all the characters to uppercase, resulting in 'HELLO WORLD'.

toLowerCase():

This method converts all the characters in a string to lowercase letters

				
					const str = 'HELLO WORLD';

const lowerCaseStr = str.toLowerCase();

console.log(lowerCaseStr); // Output: hello world

				
			

Checking and Modifying:

concat(string1, string2, …):

This method concatenates the string arguments to the calling string and returns a new string.

				
					const str1 = 'Hello';
const str2 = 'World';

const newStr = str1.concat(' ', str2);

console.log(newStr); // Output: Hello World

				
			

trim():

This method removes whitespace from both ends of a string.

				
					const str = '   Hello World   ';

const trimmedStr = str.trim();

console.log(trimmedStr); // Output: Hello World

				
			

trimStart():

This method removes whitespace from the beginning (left side) of a string.

				
					const str = '   Hello World   ';

const trimmedStartStr = str.trimStart();

console.log(trimmedStartStr); // Output: Hello World   

				
			

trimEnd():

This method removes whitespace from the end (right side) of a string

				
					const str = '   Hello World   ';

const trimmedEndStr = str.trimEnd();

console.log(trimmedEndStr); // Output:    Hello World

				
			

startsWith(searchString, position):

This method checks whether a string starts with the characters of a specified string. It returns true if the string starts with the characters; otherwise, it returns false.

				
					const str = 'Hello World';

console.log(str.startsWith('Hello')); // Output: true
console.log(str.startsWith('World')); // Output: false
    
				
			

endsWith(searchString, position):

This method checks whether a string ends with the characters of a specified string. It returns true if the string ends with the characters; otherwise, it returns false.

				
					const str = 'Hello World';

console.log(str.endsWith('World')); // Output: true
console.log(str.endsWith('Hello')); // Output: false

				
			

includes(searchString, position):

This method checks whether a string contains the specified string or characters. It returns true if the string contains the characters; otherwise, it returns false.

				
					const str = 'Hello World';

console.log(str.includes('Hello')); // Output: true
console.log(str.includes('Universe')); // Output: false

				
			

padStart(targetLength, padString):

This method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left side) of the current string.

				
					const str = '5';

console.log(str.padStart(3, '0')); // Output: 005
console.log(str.padStart(5, '123')); // Output: 12351

				
			

padEnd(targetLength, padString):

This method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the end (right side) of the current string.

				
					const str = '5';

console.log(str.padEnd(3, '0')); // Output: 500
console.log(str.padEnd(5, '123')); // Output: 51231

				
			

repeat(count):

This method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

				
					const str = 'hello';

console.log(str.repeat(3)); // Output: hellohellohello

				
			

Splitting and Joining:

split(separator, limit):

This method splits a string into an array of substrings based on a specified separator. Optionally, you can specify a limit, which limits the number of splits performed.

				
					const str = 'apple,banana,orange';

const fruitsArray = str.split(',');

console.log(fruitsArray); // Output: ['apple', 'banana', 'orange']

				
			

In this example, the split() method splits the string 'apple,banana,orange' into an array of substrings using the comma , as the separator.

Optionally, you can also specify a limit:

				
					const str = 'apple,banana,orange';

const fruitsArray = str.split(',', 2);

console.log(fruitsArray); // Output: ['apple', 'banana']

				
			

Here, the limit is set to 2, so the splitting stops after two elements.

join(separator):

This method joins the elements of an array into a single string, using a specified separator between each element

				
					const fruitsArray = ['apple', 'banana', 'orange'];

const fruitsString = fruitsArray.join(', ');

console.log(fruitsString); // Output: 'apple, banana, orange'

				
			

JavaScript strings are versatile, allowing representation of text from simple words to complex data. Methods like `localeCompare` facilitate locale-sensitive comparisons. Accessing characters and extracting substrings are made easy with methods like `charAt`, `slice`, and `indexOf`. String manipulation is convenient through methods like `replace`, `concat`, `trim`, `padStart`, `padEnd`, and `repeat`. Lastly, splitting strings into arrays using `split` and joining arrays into strings with `join` enable efficient data processingHappy coding !❤️.

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India