string(JavaScript Variable data type)

04/18/2023

Japanese version.

The string data type in JavaScript is used to represent text as a sequence of characters. Strings are represented as string literals enclosed in either double quotes ("") or single quotes ('').

Here is an example of string literals:

let message = "Hello, world!";
let name = 'Alice';

Use of quotes

Double quotes ("") and single quotes ('') are the most common ways to create string literals in JavaScript. Generally, which one to use is a matter of personal preference or a team's coding convention. However, if you need to include quotes inside a string literal, you should surround the string literal with the opposite type of quote, and escape the same type of quote.

For example, if you create a string literal with double quotes, and you need to include a single quote inside the string, you should escape the single quote:

let message = "He said, \"I'm a programmer.\"";

Likewise, if you create a string literal with single quotes, and you need to include a double quote inside the string, you should escape the double quote:

let message = 'He said, "I\'m a programmer."';

Creating Strings

There are several ways to create a string in JavaScript. Here are the main methods:

String literals

A string literal is a string enclosed in quotes, either double quotes ("") or single quotes ('').

let greeting = "Hello, world!";
let message = 'I\'m a JavaScript developer.';

If you need to include quotes inside a string literal, you can use the escape character \.

String constructor

Another way to create a string is to use the String constructor.

let str1 = new String("Hello, world!");
let str2 = new String('I\'m a JavaScript developer.');

However, using string literals is generally recommended.

Backticks (Template literals)

Starting from ES6 (ECMAScript 2015), you can use backticks (`) to create a special kind of string called a template literal. Template literals allow you to embed variable values or expressions, and can include line breaks.

You can embed variable names or expressions in a template literal by wrapping them with ${}.

let name = "Alice";
let age = 25;

let message = `My name is ${name} and I am ${age} years old.`;

Typical String Operations

Concatenating Strings

+ operator

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // John Doe

concat()

let firstName = "John";
let lastName = "Doe";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // John Doe

Template literals

let firstName = "John";
let lastName = "Doe";
let fullName = `${firstName} ${lastName}`;
console.log(fullName); // John Doe

join method

let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");
console.log(fruitString); // apple, banana, orange

The join method can be used to concatenate the elements of an array with a specified delimiter.

Getting the Length

To get the length of a string in JavaScript, you can use the length property. This property allows you to retrieve the length of a string.

Here's an example:

let str = "Hello, World!";
console.log(str.length); // 13

In this example, we're getting the length of the string "Hello, World!". The length property returns the number of characters in the string.

Splitting Strings

To split a string in JavaScript, you can use the split() method. The split() method splits a string based on a specified delimiter and stores the resulting substrings in an array.

Here's an example:

let str = "apple,banana,orange";
let fruits = str.split(",");
console.log(fruits); // ["apple", "banana", "orange"]

In this example, we're using the split() method to split the string "apple,banana,orange" based on the delimiter ,. The split() method returns an array fruits containing the resulting substrings.

You can also use regular expressions with the split() method to split a string. For example, to split a string based on whitespace characters, you can use the following code:

let str = "apple banana orange";
let fruits = str.split(/\s+/);
console.log(fruits); // ["apple", "banana", "orange"]

In this example, we're using the regular expression \s+ to split the string based on whitespace characters.

Extracting Substrings

In JavaScript, there are three methods available to extract a substring from a string: substring(), substr(), and slice().

These methods are commonly used for extracting substrings from strings. The differences are in the way the start and end positions are specified, or in the way the length is specified.

substring()

The substring() method returns the substring between the specified start and end positions. The start and end positions are specified as string indices. If the start position is greater than the end position, the parameters are swapped. If the end position is omitted, the substring includes all characters until the end of the string.

Here's an example:

let str = "Hello, World!";
let result = str.substring(7, 12);
console.log(result); // "World"

substr()

The substr() method returns the substring with the specified length from the specified start position. The start position is specified as a string index. If the length is omitted, the substring includes all characters from the start position to the end of the string.

Here's an example:

let str = "Hello, World!";
let result = str.substr(7, 5);
console.log(result); // "World"

slice()

The slice() method returns the substring between the specified start and end positions. The start and end positions are specified as string indices. If the end position is omitted, the substring includes all characters until the end of the string. Negative values can be used for the start and end positions to count positions from the end of the string.

Here's an example:

let str = "Hello, World!";
let result = str.slice(7, 12);
console.log(result); // "World"

Replacing Substrings

replace()

To replace a string in JavaScript, you can use the replace() method. The replace() method returns a new string with the specified string pattern replaced by another string. However, only the first occurrence of the pattern is replaced.

In the following example, the first occurrence of "world" in the string str is replaced with "universe":

let str = "Hello, World!";
let result = str.replace("world", "universe");
console.log(result); // "Hello, universe!"

In this example, only the first occurrence of "world" is replaced, and the original string str is not changed. The new string with the replacement is stored in the result variable.

You can also use regular expressions to specify the pattern for the replace() method. In the following example, all digits in the string str are replaced with "X" using a regular expression:

let str = "12345";
let result = str.replace(/\d/g, "X");
console.log(result); // "XXXXX"

In this example, the \d regular expression pattern is used to specify all digits. The g flag is used to perform the replacement on all matching strings.

replaceAll()

replaceAll() is a method introduced in ECMAScript 2021 for replacing all occurrences of a substring within a string.

In the following example, all occurrences of "world" in the string str are replaced with "universe":

let str = "Hello, world! Hello, world!";
let result = str.replaceAll("world", "universe");
console.log(result); // "Hello, universe! Hello, universe!"

In this example, all occurrences of "world" are replaced with "universe", and the original string str is not changed. The new string with the replacements is stored in the result variable.

Changing Case

toUpperCase()

The toUpperCase() method converts all characters in a string to uppercase. For example, the following code converts the str variable to uppercase:

let str = "Hello, World!";
let result = str.toUpperCase();
console.log(result); // "HELLO, WORLD!"

toLowerCase()

The toLowerCase() method converts all characters in a string to lowercase. For example, the following code converts the str variable to lowercase:

let str = "Hello, World!";
let result = str.toLowerCase();
console.log(result); // "hello, world!"

Trimming Whitespace

In JavaScript, trimming a string means removing whitespace characters from the beginning and/or end of a string. Whitespace characters include spaces, tabs, and newlines.

trim()

The trim() method removes whitespace from the beginning and end of a string. For example, the following code removes whitespace before and after the str variable.

let str = "   Hello, World!    "
let result = str.trim();
console.log(result); // "Hello, World!"

trimStart()

The trimStart() method removes leading whitespace from a string. For example, the following code removes leading whitespace from the str variable.

let str = "   Hello, World!";
let result = str.trimStart();
console.log(result); // "Hello, World!"

trimEnd()

The trimEnd() method removes trailing whitespace from a string. For example, the following code removes trailing whitespace from the str variable.

let str = "Hello, World!    ";
let result = str.trimEnd();
console.log(result); // "Hello, World!"

Searching Strings

JavaScript provides built-in functions to search for patterns in a string. Here are some commonly used string search functions.

indexOf()

The indexOf() method in JavaScript returns the index of the first occurrence of a specified substring in a string. If the substring is not found, it returns -1.

You can use indexOf() like this:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.indexOf("fox")); // 16
console.log(str.indexOf("cat")); // -1

In the above example, the index of the first occurrence of the substring "fox" in the string "The quick brown fox jumps over the lazy dog." is 16. The substring "cat" is not found, so -1 is returned.

indexOf() starts searching from the beginning of the specified string and returns the index of the first occurrence found. If the same substring appears multiple times in the string, the index of the first occurrence is returned. Additionally, indexOf() is case-sensitive, so if the substring is in uppercase letters, the search string must also be in uppercase.

lastIndexOf()

The lastIndexOf() method in JavaScript returns the index of the last occurrence of a specified substring in a string. If the substring is not found, it returns -1.

You can use lastIndexOf() like this:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.lastIndexOf("o")); // 41
console.log(str.lastIndexOf("cat")); // -1

In the above example, the index of the last occurrence of the character "o" in the string "The quick brown fox jumps over the lazy dog." is 41. The substring "cat" is not found, so -1 is returned.

lastIndexOf() starts searching from the end of the specified string and returns the index of the last occurrence found. If the same substring appears multiple times in the string, the index of the last occurrence is returned. Additionally, lastIndexOf() is case-sensitive, so if the substring is in uppercase letters, the search string must also be in uppercase.

search()

The search() method in JavaScript returns the index of the first occurrence of a string that matches a specified regular expression. If no match is found, it returns -1.

You can use search() like this:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.search(/fox/)); // 16
console.log(str.search(/cat/)); // -1

In the above example, the index of the first occurrence of the string that matches the regular expression /fox/ in the string "The quick brown fox jumps over the lazy dog." is 16. The regular expression /cat/ is not found, so -1 is returned.

search() returns the index of the first occurrence of a string that matches the specified regular expression. If the same string appears multiple times in the string, the index of the first occurrence is returned.

search() can be used in a similar way to indexOf(), but indexOf() cannot use regular expressions to search for strings. In contrast, search() can use regular expressions for searching.

match()

match() returns an array of strings matching a given regular expression.

Using the flag g for a regular expression returns all matches as an array if it matches more than once in a string.

Use flag i to search for a case-insensitive match in a string.

JavaScript's match() method searches for strings matching a given regular expression and returns them as an array.

If the g flag is not included, an array containing the first matching string is returned. If no matching string is found, null is returned.

match() can be used as follows:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.match(/fox/)); // ["fox", index: 16, input: "The quick brown fox jumps over the lazy dog.", groups: undefined]
console.log(str.match(/o/g)); // ["o", "o", "o", "o"]
console.log(str.match(/cat/)); // null

startsWith()

The startsWith() method in JavaScript string operations is used to determine if a string begins with a specified string or character. If the string begins with the specified string or character, it returns true, otherwise it returns false.( boolean value)

Here's an example of using the startsWith() method:

const str = "Hello, world!";
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("World")); // false
console.log(str.startsWith("Hello,")); // true
console.log(str.startsWith("He")); // true
console.log(str.startsWith("hello")); // false

In the above example, the startsWith() method is used to determine if the string begins with a specified string or character. Note that the startsWith() method is case sensitive, so if you specify a different string like "World" or "hello", you may not get the correct result.

Additionally, the startsWith() method can take a second argument to specify the position at which to start the search. This can be useful when searching only a part of the string. Here is an example of using the startsWith() method to start searching from a part of the string:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.startsWith("brown", 10)); // true
console.log(str.startsWith("lazy", 30)); // true

In the above example, the second argument is passed to the startsWith() method to specify the position at which to start the search. Since "brown" is included in a substring starting at the index 10, it returns true. Similarly, since "lazy" is included in a substring starting at the index 30, it returns true.

endsWith()

The endsWith() method in JavaScript string operations is used to determine if a string ends with a specified string or character. If the string ends with the specified string or character, it returns true, otherwise it returns false. ( boolean value)

Here's an example of using the endsWith() method:

const str = "Hello, world!";
console.log(str.endsWith("world!")); // true
console.log(str.endsWith("Hello")); // false
console.log(str.endsWith("ld!")); // true
console.log(str.endsWith("o")); // false
console.log(str.endsWith("ld")); // false

In the above example, the endsWith() method is used to determine if the string ends with a specified string or character. Note that the endsWith() method is case sensitive, so if you specify a different string like " World!" or "LD!", you may not get the correct result.

Additionally, the endsWith() method can take a second argument to specify the position at which to end the search. This can be useful when searching only a part of the string. Here is an example of using the endsWith() method to end the search from a part of the string:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.endsWith("brown", 15)); // true
console.log(str.endsWith("dog.", str.length)); // true

n the example above, the second argument is passed to the endsWith() method to specify the position at which to end the search. Since "brown" is included in a substring up to the 15th character (index 14), it returns true. Similarly, since "dog." is included at the end of the string, passing str.length as the second argument to endsWith() ensures the entire string is searched, returning true.

includes()

The includes() method is used to determine whether a specified string is contained within the current string. This method returns a boolean value.

For example, you can use code like the following to check whether a string contains a specific substring:

let str = "Hello, World!";
console.log(str.includes("Hello")); // true
console.log(str.includes("world")); // false

This method is case-sensitive. Therefore, in the example above, if you specify "World" instead of "world", the method will return true.

Additionally, the includes() method can also be used to specify the position to start the search by providing a second argument. In this case, the search will start from the specified position.

For example, you can check whether a specified substring is included in the string, ignoring the first 5 characters, like this:

let str = "Hello, World!";
console.log(str.includes("World", 5)); // true

In the above example, the search starts from the 5th position, so "World" is found.

---

Links

JavaScript Articles