the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: Exploring JavaScript Substring: Real-World Use Cases with Examples
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > Javascript > Exploring JavaScript Substring: Real-World Use Cases with Examples
Javascript

Exploring JavaScript Substring: Real-World Use Cases with Examples

thegeekycodes By thegeekycodes 14 August 2023 8 Min Read
javascript substring
SHARE

Javascript string substring() is a powerful function that extracts a portion of a string based on given index values. In this article, we’ll delve into the workings of the substring() function and explore real-world use cases where it can prove invaluable.

Contents
Understanding the substring() FunctionSubstrings can take negative index numbersReal-World Use CasesExtracting Domains from URLsFormatting UsernamesTrimming Excess TextWorking with Time FormatsExtracting Metadata from StringsManipulating File PathsFormatting Phone NumbersDynamic Data MaskingExtracting CoordinatesReferenceConclusion

Understanding the substring() Function

substring() is a built-in JavaScript string manipulation method that allows you to extract a portion of a string based on given index values. The method returns a new string output containing characters from the original string starting at the given starting index and ending at the specified end index (or the end of the string, if the end index is not provided).

The syntax for the substring() the method is as follows:

const subStringResult = string.substring(startIndex, endIndex);

Here’s a breakdown of the parameters:

  • string: The original string from which you want to extract a substring.
  • startIndex: The index at which the extraction should start (inclusive).
  • endIndex: (Optional) The index at which the extraction should stop. If not provided, the extraction will continue until the end of the string.

Please note substring() method doesn’t modify the original string; it returns a new string that contains the extracted substring.

Here are a few examples to illustrate the usage of the substring() method:

const originalString = "Hello, world!";
const substring1 = originalString.substring(7); // Extracts "world!"
const substring2 = originalString.substring(0, 5); // Extracts "Hello"
const substring3 = originalString.substring(7, 12); // Extracts "world"

In these examples, substring1 extracts characters from index 7 to the end of the string, substring2 extracts characters from index 0 to index 4, and substring3 extracts characters from index 7 to index 11.

Substrings can take negative index numbers

The substring() method in JavaScript can accept negative numbers as parameters for both the start and end indices. When you pass negative indices, they are counted from the end of the string. The last character of the string is at index -1, the second-to-last character is at index -2, and so on.

Here’s how negative indices work with the substring() method:

const originalString = "Hello, world!";
const substring1 = originalString.substring(-6); // Equivalent to substring(0)
const substring2 = originalString.substring(-12, -7); // Equivalent to substring(0, 5)
const substring3 = originalString.substring(7, -1); // Equivalent to substring(7, 11)

In these examples:

  • substring1 is equivalent to using substring(0) because negative -6 becomes 0.
  • substring2 is equivalent to using substring(0, 5) because negative -12 becomes 0 and negative -7 becomes 5.
  • substring3 is equivalent to using substring(7, 11) because negative -1 becomes the index of the last character.

Negative indices can be particularly useful when you want to extract a substring from the end of a string without needing to calculate the exact index yourself. Just remember that using negative indices with the substring() method is a convenient way to work with strings, allowing you to easily handle substrings from both the beginning and end of the string.

Real-World Use Cases

Extracting Domains from URLs

Imagine you’re building a web application that requires extracting domain names from a list of URLs. The substring() function can come to the rescue. Here’s how:

const urls = [
  "https://www.test.com/page1",
  "https://blog.sample.com/article",
  "https://api.data.org/data"
];

const domains = urls.map(url => {
  const startIndex = url.indexOf("//") + 2;
  const endIndex = url.indexOf("/", startIndex);
  return url.substring(startIndex, endIndex);
});

console.log(domains); //[ 'www.test.com', 'blog.sample.com', 'api.data.org' ]

Formatting Usernames

When dealing with usernames, you might want to display only the first few characters, followed by an ellipsis. Let’s see how substring() can help:

const username = "adventureSeeker123";
const formattedUsername = username.length > 10
  ? username.substring(0, 10) + "..."
  : username;

console.log(formattedUsername);

Trimming Excess Text

In scenarios where you’re displaying dynamic content like comments, you may want to trim the text to a certain length and add a “Read More” link. Here’s how you could do it:

const comment = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
const maxDisplayLength = 30;

const trimmedComment = comment.length > maxDisplayLength
  ? comment.substring(0, maxDisplayLength) + "..."
  : comment;

console.log(trimmedComment);

Working with Time Formats

Suppose you’re working on a time tracking application and need to extract hours and minutes from a time string. The substring() function can be employed:

const timeString = "09:45";
const hours = parseInt(timeString.substring(0, 2));
const minutes = parseInt(timeString.substring(3));

console.log(`Hours: ${hours}, Minutes: ${minutes}`);

Extracting Metadata from Strings

Consider a scenario where you’re processing strings containing metadata in a specific format, such as “Title – Author.” You can use the substring() function to extract individual components:

const metadataString = "JavaScript Substring - John Doe";
const separatorIndex = metadataString.indexOf(" - ");

if (separatorIndex !== -1) {
  const title = metadataString.substring(0, separatorIndex);
  const author = metadataString.substring(separatorIndex + 3);
  console.log(`Title: ${title}, Author: ${author}`);
} else {
  console.log("Invalid metadata format");
}

Manipulating File Paths

When working with file paths, you might need to extract the file name and its extension. Let’s see how substring() can help:

const filePath = "/documents/reports/report1.pdf";
const fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
const fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);

console.log(`File Name: ${fileName}, Extension: ${fileExtension}`);

Formatting Phone Numbers

In scenarios where you’re displaying phone numbers, you may want to format them consistently. The substring() function can be used to rearrange digits:

const phoneNumber = "1234567890";
const formattedNumber = `(${phoneNumber.substring(0, 3)}) ${phoneNumber.substring(3, 6)}-${phoneNumber.substring(6)}`;

console.log(`Formatted Number: ${formattedNumber}`);

Dynamic Data Masking

If you’re handling sensitive information like credit card numbers, you might want to mask parts of the data. Here’s how substring() can assist:

const creditCardNumber = "1234 5678 9012 3456";
const maskedNumber = creditCardNumber.substring(0, 12).replace(/\d/g, "*") + creditCardNumber.substring(12);

console.log(`Masked Number: ${maskedNumber}`);

Extracting Coordinates

If you’re working with geographical data in the form of coordinates, you can use the substring() function to extract latitude and longitude:

const coordinates = "40.7128° N, 74.0060° W";
const latitude = parseFloat(coordinates.substring(0, coordinates.indexOf("°")));
const longitude = parseFloat(coordinates.substring(coordinates.indexOf(", ") + 2, coordinates.lastIndexOf("°")));

console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);

Reference

developer.mozilla.org

Conclusion

The JavaScript substring() function continues to prove its versatility in various real-world scenarios. By creatively implementing it, developers can simplify complex tasks, enhance user experiences, and ensure consistent data presentation across their applications. Whether you’re working with URLs, formatting strings, or manipulating data, the substring() function remains a valuable asset in your programming toolkit. Experiment with these examples and adapt them to your projects, taking full advantage of what this function has to offer. Happy coding!

TAGGED: javascript, JavaScript substring examples, String manipulation in JavaScript, strings, Substring

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article Build google Chrome extension to take a screenshot Build a Google Chrome extension to take a screenshot of the current webpage
Next Article Python List Comprehension Python List Comprehension: Simplifying Iteration with Powerful Syntax
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
Google Analytics 4 in Nextjs 14
How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024

You Might Also Like

Understanding Server Actions in Nextjs
TutorialJavascriptNextjsReact js

Understanding Server Actions in Nextjs

7 Min Read
Implementing Dark Mode with JavaScript
TutorialJavascript

Implementing Dark Mode with JavaScript

3 Min Read
Build a Simple Calculator App with React
TutorialReact js

Build a Simple Calculator App with React, Tailwind CSS. Displays History

8 Min Read
Automating Google Sheets to Send Email Reminders
TutorialGoogle SheetsJavascript

Automating Google Sheets to Send Email Reminders

5 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?