JAVASCRIPT

JavaScript String: Strings and String Methods in JS

In JavaScript, a string is a sequence of characters within single quotes ('), double quotes ("), or backticks (```). Strings represent text and can consist of any characters, including letters, numbers, and special characters.

How to Use JavaScript Strings

To create a basic string, you can use single or double quotes. Template literals with backticks allow you to embed expressions and create formatted strings with multiple lines.

// Single and double quotes for strings
const greeting = 'Hello, World!';
const response = "I'm learning JavaScript!";

// Template literals for more complex scenarios
const user = {
  firstName: 'Jane',
  lastName: 'Doe'
};
const welcomeMessage = `Welcome, ${user.firstName} ${user.lastName}!`;

When to Use JavaScript Strings

In JavaScript, you need strings for working with text or textual data. From displaying or handling user input to storing text in variables, strings are useful in many different ways.

Working with Text

The most basic use of strings is representing text as values or within variables.

const message = "Hello, World!";
console.log(message);

Interacting with Users

Strings manage user inputs and display messages, playing a crucial role in dynamic content on web pages.

const userName = prompt("What's your name?");
alert(`Hello, ${userName}!`);

Processing Data

Strings are essential for formatting, constructing, and parsing data within applications.

const rawData = 'name,age,email';
const userDetails = rawData.split(',');
console.log(userDetails); // Outputs: ['name', 'age', 'email']

Examples of JavaScript Strings

Strings are a key component of almost any web application in JavaScript. Here are some common applications:

Registration Forms

Within registration forms, strings help validate user inputs, such as checking the format of email addresses or passwords.

const email = 'user@example.com';
if (email.includes('@')) {
  console.log('Valid email address.');
} else {
  console.log('Invalid email address.');
}

URL

Strings are essential for building URLs, which are critical to navigating between web pages and accessing APIs.

const baseUrl = 'http://api.example.com';
const userId = '123';
const url = `${baseUrl}/users/${userId}`;
console.log(url); // Outputs: 'http://api.example.com/users/123'

Learn More About JavaScript Strings

Adding and Joining Strings

You can combine multiple strings into a single string using the + operator, the join() method, and template literals. The + operator is straightforward and perfect when the number of strings to combine is low and known in advance.

// Using the + operator to concatenate strings
const firstName = 'John';
const lastName = 'Doe';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // Outputs: John Doe

const greeting = "Hello, " + fullName + "!";
console.log(greeting); // Outputs: Hello, John Doe!

The join() method shines when you need to concatenate multiple strings from an array. join() takes an array and a separator string and returns the combined string of elements, separated by the separator.

// Using the .join() method for arrays
const words = ['Hello', 'world', 'from', 'JavaScript'];
const sentence = words.join(' ');  // The space here is the separator
console.log(sentence); // Outputs: Hello world from JavaScript

const pathComponents = ['home', 'user', 'documents', 'file.txt'];
const filePath = pathComponents.join('/');  // Using slash as a separator for file paths
console.log(filePath); // Outputs: home/user/documents/file.txt

Template literals use backticks (```) rather than quotes and are a great alternative to the + operator and the join() method. With template literals, you can embed expressions within a string to assemble well-formatted strings.

// Concatenation using template literals
const user = { firstName: 'Jane', lastName: 'Doe' };
const welcomeMessage = `Welcome, ${user.firstName} ${user.lastName}!`;
console.log(welcomeMessage); // Outputs: Welcome, Jane Doe!

const product = { name: 'Book', price: 19.99 };
const productDescription = `Product: ${product.name}\\nPrice: $${product.price}`;
console.log(productDescription);
/*
Outputs:
Product: Book
Price: $19.99
*/

Parsing and Formatting Strings

JavaScript strings are ideal for parsing data from various formats and putting together user-facing messages. Template literals offer a powerful way to embed variables and expressions into strings.

const price = 19.99;
const quantity = 3;
console.log(`Total Price: ${price * quantity}`); // Outputs: Total Price: 59.97

const userData = "name:John,age:30";
const userDetails = Object.fromEntries(userData.split(',').map(item => item.split(':')));
console.log(userDetails); // {name: "John", age: "30"}

Escaping Characters in Strings

Escape sequences allow you include characters in strings that are part of JavaScript or have no direct expression. These special characters include new lines, tabs, quotes, and other characters that have a specific meaning in JavaScript. Many escape sequences use a backslash (\) and the character you want to use within the string.

const message = 'He said, "JavaScript is awesome"';
const path = "C:\\\\Projects\\\\new";

console.log(message); // Outputs: He said, "JavaScript is awesome"
console.log(path); // Outputs: C:\Projects\new

Common escape sequences include:

  • \\: Backslash
  • \': Single quote
  • \": Double quote
  • \n: New line
  • \t: Tab

Regular Expressions in JavaScript

Regular expressions (regex) can help you find or validate strings of text, like certain characters, words, or patterns. You can create a regular expression by enclosing a pattern between two slashes (/) or using the RegExp constructor.

// Regular expression literal
const regex = /hello/;
// RegExp constructor
const regexWithConstructor = new RegExp('hello');

To check if a string matches a pattern, you can use the string test() method. The method returns true if it identifies a match and false if it doesn’t.

const regex = /hello/;
const message = "Mimohello GmbH";
console.log(regex.test(message)); // Outputs: true

You can also use a regular expression to check if a string stores a valid email address.

const emailRegex = /^\w+@\w+\.\w+$/;
const email = "example@email.com";
console.log(emailRegex.test(email)); // Outputs: true if valid

Splitting Strings in JavaScript

In JavaScript, you can split a string into an array of strings based on a specified separator with the split() method. split() accepts up to two parameters: the separator string and an optional limit on the number of splits. The method returns an array of strings without the separator.

const fruits = "apple, banana, cherry";
const fruitList = fruits.split(", ");
console.log(fruitList); // Outputs: ['apple', 'banana', 'cherry']

JavaScript String Contains Another String

You can check if a string contains a substring by using the includes() method in JavaScript. includes() accepts up to two arguments: the substring to search for and an optional position at which to begin searching. The method returns true if it finds the specified substring and false if it doesn’t.

const sentence = "Hello, world!";
const word = "world";
console.log(sentence.includes(word)); // Outputs: true

You can also use the indexOf() method to check if a string contains a substring and get the substring's position. indexOf() takes the same arguments as includes() but returns the index of the first occurrence of the substring instead of true. If it fails to find the specified substring, it returns -1.

const greeting = "Hello, world!";
const searchTerm = "world";
const index = greeting.indexOf(searchTerm);

if (index !== -1) {
  console.log(`'${searchTerm}' found at position ${index}`); // Outputs: 'world' found at position 7
} else {
  console.log(`'${searchTerm}' not found`);
}

Empty Strings in JavaScript

In JavaScript, an empty string is a string that contains no characters (""). Empty strings are useful for handling and validating user input, setting default values, and working with loops and conditionals.

const emptyStr = "";

You can check if a string is empty by comparing it to an empty string, using length, or with logical evaluation.

// Direct comparison
const isEmpty = emptyStr === "";

// Using length property
const isEmptyUsingLength = emptyStr.length === 0;

// Logical evaluation
const isAlsoEmpty = !emptyStr; // Coerces to false because empty strings are falsy

Advanced String Methods

JavaScript features an extensive array of advanced string methods for working with textual data.

  • toUpperCase(): Converting all characters in a string to uppercase, toUpperCase() is useful for normalizing case-insensitive data.
  • toLowerCase(): Converting all characters in a string to lowercase, toUpperCase() is also great for normalizing case-insensitive data.

const mixedCaseString = 'JaVaScRiPt';
console.log(mixedCaseString.toLowerCase()); // Outputs: "javascript"
console.log(mixedCaseString.toUpperCase()); // Outputs: "JAVASCRIPT"
  • trim(): Removing whitespace from the beginning and the end of a string, trim() is useful for cleaning text.
  • trimStart() or trimLeft(): Removes whitespace only from the start of the string.
  • trimEnd() or trimRight(): Removes whitespace only from the end of the string.

const extraSpace = '   Hello, world!   ';
console.log(extraSpace.trim()); // "Hello, world!"
console.log(extraSpace.trimStart()); // "Hello, world!   "
console.log(extraSpace.trimEnd()); // "   Hello, world!"
  • replace(): Replacing occurrences of a substring with a new string, replace() is ideal for cleaning and formatting text.

const greeting = 'Hello, world!';
console.log(greeting.replace('world', 'JavaScript')); // "Hello, JavaScript!"
 
  • slice(): Extracts a section of a string and returns it as a new string without modifying the original string.
  • charAt(): Returns a single character at a specified index.

const exampleString = "JavaScript";
console.log(exampleString.slice(0, 4)); // "Java"
console.log(exampleString.charAt(0)); // "J"
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH