Skip to main content

Building Blocks in JS

Datatypes in-depth - Strings

When we think about handling text in JavaScript, we're diving into the world of strings. Strings are everywhere in programming, whether you're building a website, writing an app, or even working with APIs. They represent textual data, and in JavaScript, they come with some unique features that make them both powerful and easy to work with.

The Basics of Strings

In JavaScript, strings are sequences of characters used to represent text. You can think of them as arrays of characters, although they differ in some critical ways (we’ll get to that later). Unlike languages like C, which differentiate between single characters and strings, JavaScript treats everything as a string.

const name = "Shrikanth";
const A = "A";
let greeting = "Namaste LearnYard!";

Here, "Namaste Learnyard!" is a string, and greeting is a variable that holds that string.

Types of Quotes

You can create strings using single quotes, double quotes, or backticks. The choice of which to use depends on the context and personal preference.

Single Quotes ( ' ' )

let welcome = 'Welcome to the world of JavaScript!';

Double quotation marks ( " " )

let codersGyan = "Eat, Sleep, Code, Repeat!";

Backticks (`):

These are more versatile as they allow you to embed expressions and span multiple lines.

let message = `Dear customer, 
Your order #12345 is confirmed.
Thank you for shopping with us!`;

Imagine you're building an online store, let's call it BharatBazar, where you greet customers when they visit your site. Depending on the time of day, you might want to show a different message.

Here’s how you can use strings in JavaScript to implement this:

let timeOfDay = "morning"; // This could be dynamically set based on the user's local time
let customerName = "Amit";

let greetingMessage;

if (timeOfDay === "morning") {
    greetingMessage = `Good morning, ${customerName}! Welcome to BharatBazar.`;
} else if (timeOfDay === "afternoon") {
    greetingMessage = `Good afternoon, ${customerName}! Hope you're having a great day.`;
} else {
    greetingMessage = `Good evening, ${customerName}! Enjoy shopping at BharatBazar.`;
}

console.log(greetingMessage);

In this example, we use backticks to create a string that can include dynamic content—specifically, the customerName and the appropriate greeting based on the time of day.

Special Characters in Strings

JavaScript strings can include special characters, which are represented by escape sequences starting with a backslash (\). These characters are useful for formatting text.

Some common special characters include:

  • Newline (\n): Adds a line break.
  • Tab (\t): Adds a tab space.
  • Backslash (\\): Adds a literal backslash.
  • Quotes (\', \"): Adds a literal single or double quote.

Let's tweak our earlier example to add some special characters:

let message = `Dear ${customerName},\n\n\tThank you for shopping with us at BharatBazar.\n\tYour satisfaction is our priority!`;

console.log(message);

The output will be:

Dear Amit,

    Thank you for shopping with us at BharatBazar.
    Your satisfaction is our priority!

String Length

The length of a string is simply the number of characters it contains. You can get the length of a string using the .length property.

In javascript even primitives can have methods on them, we will be discussing more about this in the section - Object wrappers and Methods of primitives article.

let storeName = "BharatBazar";
console.log(storeName.length); // 11

Accessing Characters in a String

You can access individual characters in a string using square brackets ([]), or the .at() method.

let storeName = "BharatBazar";

console.log(storeName[0]); // 'B'
console.log(storeName.at(-1)); // 'r'

Using .at() is particularly useful when you need to access characters from the end of the string.

Strings Are Immutable

One key aspect of strings in JavaScript is their immutability. This means that once a string is created, it cannot be changed. Any operation that appears to modify a string will actually create a new string.

For example:

let store = "BharatBazar";
store[0] = 'b'; // This won't change the string

console.log(store); // Still "BharatBazar"

If you want to change the string, you have to create a new one:

let store = "BharatBazar";
store = 'b' + store.slice(1); // "bharatBazar"

console.log(store); // "bharatBazar"

Changing Case

JavaScript provides methods to change the case of a string: .toUpperCase() and .toLowerCase().

let product = "Laptop";
console.log(product.toUpperCase()); // "LAPTOP"
console.log(product.toLowerCase()); // "laptop"

Searching within a String

To search for a substring within a string, JavaScript offers several methods:

.indexOf(): Returns the index of the first occurrence of the substring. If not found, it returns -1.

Shrikanth's Pro tip! - I want to quickly remind you all to run the code snippets I have shared here and run them in the browser console at the least to ensure you learn by doing it, just reading will not help for your interviews!

Alright, let's get back to it

.includes(): Returns true or false depending on whether the substring exists within the string.

console.log(storeName.includes("Bazar")); // true

.startsWith() and .endsWith(): These methods check if a string starts or ends with a specific substring.

console.log(storeName.startsWith("Bharat")); // true
console.log(storeName.endsWith("Bazaar")); // false

Let’s say you’re offering a special discount at BharatBazar, and customers need to enter a code to avail of it. The code should start with "BB-" to be valid, just a simple example here, of course in real life we will have much more validations.

let discountCode = "BB-12345";
let isValid = discountCode.startsWith("BB-");

if (isValid) {
    console.log("Discount applied successfully!");
} else {
    console.log("Invalid discount code.");
}

Extracting Substrings

There are several methods to extract parts of a string:

.slice(start, end): Extracts the part of the string from start to end (not inclusive).

let fullName = "Amitabh Bachchan";
let firstName = fullName.slice(0, 7);
console.log(firstName); // "Amitabh"

.substring(start, end): Similar to .slice() but doesn’t support negative indices.

let lastName = fullName.substring(8);
console.log(lastName); // "Bachchan"

.substr(start, length): Extracts the part of the string starting from start and of the specified length.

let middlePart = fullName.substr(3, 4);
console.log(middlePart); // "itab"

Comparing Strings

Strings are compared based on their Unicode values. However, this can lead to some quirks, especially with international characters.

For instance:

console.log("Amitabh" > "amitabh"); // false
console.log("Amitabh" > "Bachchan"); // false

Lowercase letters have higher Unicode values than uppercase letters, which is why "Amitabh" > "amitabh" returns false.

Sorting Product Names

If you’re sorting product names in your BharatBazar store, you might encounter these issues right, so how to sort? To sort correctly, you can use the .localeCompare() method:

let products = ["Shampoo", "soap", "Brush", "Detergent"];
products.sort((a, b) => a.localeCompare(b));

console.log(products); // ["Brush", "Detergent", "Shampoo", "soap"]

Strings in JavaScript are incredibly versatile and powerful, allowing you to manipulate text in various ways. Whether you’re greeting customers on your e-commerce site, validating discount codes, or sorting product names, understanding how to work with strings is useful.