DEV Community

Cover image for JavaScript string manipulation technique Every Developer Should Know [Part 2]
Roman
Roman

Posted on • Originally published at programmingly.dev

1 1

JavaScript string manipulation technique Every Developer Should Know [Part 2]

In the previous article, we covered the core JavaScript string manipulation methods like slice(), substring(), replace(), and others. In this part 2, we’ll focus on more custom string manipulation functions that are particularly useful in complex or larger projects. These functions will help you handle tasks like masking sensitive information, formatting data, or performing advanced string operations.

1) Hide Credit Card Digits (Show Last 4 Digits)

When working with sensitive data such as credit card numbers, it’s important to mask the information, showing only the last four digits for security.

    function maskCreditCard(cardNumber) {
        return cardNumber.slice(-4).padStart(cardNumber.length, '*');
    }

    const creditCardNumber = "1234567812345678";
    console.log(maskCreditCard(creditCardNumber)); // "************5678"

Enter fullscreen mode Exit fullscreen mode

2) Convert a String to Title Case

Sometimes you may need to format strings so that the first letter of each word is capitalized. This is common when working with user inputs, article titles, or names.

    function toTitleCase(str) {
        return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(' ');
    }

    const sentence = "hello world from javascript";
    console.log(toTitleCase(sentence)); // "Hello World From Javascript"

Enter fullscreen mode Exit fullscreen mode

3) Truncate a String to a Specific Length

When dealing with large blocks of text, you might want to display a truncated version, followed by ellipses (...). This is useful for previews of articles or descriptions.

    function truncateString(str, length) {
        return str.length > length ? str.slice(0, length) + '...' : str;
    }

    const longText = "JavaScript is a versatile programming language used for both frontend and backend development.";
    console.log(truncateString(longText, 40)); // "JavaScript is a versatile programming lan..."

Enter fullscreen mode Exit fullscreen mode

4) Extract the Domain Name from an Email Address

When working with email addresses, you may need to extract the domain name (everything after the @ symbol). This can be useful for validating email addresses or categorizing users based on their email provider.

    function getDomainFromEmail(email) {
        return email.slice(email.indexOf('@') + 1);
    }

    const email = "user@example.com";
    console.log(getDomainFromEmail(email)); // "example.com"

Enter fullscreen mode Exit fullscreen mode

5) Remove Non-Alphanumeric Characters

In some cases, you may need to remove any non-alphanumeric characters (such as punctuation, spaces, or symbols) from a string using Regular Expressions. This can be helpful when sanitizing user input or creating URLs.

    function removeNonAlphanumeric(str) {
        return str.replace(/[^a-z0-9]/gi, '');
    }

    const messyString = "Hello! Welcome to @JavaScript_123.";
    console.log(removeNonAlphanumeric(messyString)); // "HelloWelcometoJavaScript123"

Enter fullscreen mode Exit fullscreen mode

6) Count Occurrences of a Substring in a String

You might need to count how many times a specific substring appears within a larger string. This is useful when analyzing text, such as counting occurrences of a word or phrase.

    function countOccurrences(str, substring) {
        return str.split(substring).length - 1;
    }

    const text = "JavaScript is amazing. JavaScript is versatile. JavaScript is everywhere.";
    console.log(countOccurrences(text, "JavaScript")); // 3

Enter fullscreen mode Exit fullscreen mode

7) Reverse a String

Reversing a string is a common coding exercise and can also be useful in certain algorithms, such as checking if a string is a palindrome (reads the same forwards and backward).

    function reverseString(str) {
        return str.split('').reverse().join('');
    }

    const originalString = "JavaScript";
    console.log(reverseString(originalString)); // "tpircSavaJ"

Enter fullscreen mode Exit fullscreen mode

8) Validate if a String is a Palindrome

A palindrome is a string that reads the same forwards and backward. This function checks if a given string is a palindrome.

    function isPalindrome(str) {
        const cleanedStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
        return cleanedStr === cleanedStr.split('').reverse().join('');
    }

    const word = "A man, a plan, a canal, Panama";
    console.log(isPalindrome(word)); // true

Enter fullscreen mode Exit fullscreen mode

9) Generate a Random String (for Unique IDs or Tokens)

Often in web development, you’ll need to generate random strings for unique IDs, tokens, or temporary file names.

    function generateRandomString(length) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        return result;
    }

    console.log(generateRandomString(10)); // e.g., "A7cJk1nP0X"

Enter fullscreen mode Exit fullscreen mode

10) Convert a Hyphenated or Underscored String to Camel Case

When working with variable names or CSS class names, converting a string from a hyphenated or underscored format to camelCase is a common requirement.

    function toCamelCase(str) {
        return str.replace(/[-_](.)/g, (_, char) => char.toUpperCase());
    }

    const example = "background-color";
    console.log(toCamelCase(example)); // "backgroundColor"

Enter fullscreen mode Exit fullscreen mode

11) Escape HTML Special Characters

When working with user input in web applications, it’s important to escape special characters to prevent XSS attacks or rendering issues in HTML.

    function escapeHTML(str) {
        const map = {
            '&': '&',
            '<': '<',
            '>': '>',
            '"': '"',
            "'": '''
        };
        return str.replace(/[&<>"']/g, function(match) {
            return map[match];
        });
    }

    const rawHTML = "<div>Click 'here' & \"now\"</div>";
    console.log(escapeHTML(rawHTML)); // "<div>Click 'here' & "now"</div>"

Enter fullscreen mode Exit fullscreen mode

12) Remove Duplicates from a String

If you want to remove duplicate characters from a string, you can use this custom function.

    function removeDuplicates(str) {
        return [...new Set(str)].join('');
    }

    const stringWithDuplicates = "aabbccddeeff";
    console.log(removeDuplicates(stringWithDuplicates)); // "abcdef"

Enter fullscreen mode Exit fullscreen mode

13) Slugify a String

A useful method for converting a blog article, product, and any title into a URL-friendly slug.

    function slugify(str) {
      return str
        .toLowerCase()
        .trim()
        .replace(/[^a-z0-9 -]/g, "")
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-");
    }

    console.log(slugify("Hello World from JavaScript!")); 
    // "hello-world-from-javascript"

Enter fullscreen mode Exit fullscreen mode

14) Email Validation Using Regex

Validating email addresses is crucial for ensuring the data you receive is in the correct format. You can use a regular expression to validate email addresses.

    function validateEmail(email) {
        const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return regex.test(email);
    }

    console.log(validateEmail("user@example.com")); // true
    console.log(validateEmail("user@.com")); // false

Enter fullscreen mode Exit fullscreen mode

15) Copy to Clipboard

Copying text to the clipboard can enhance user experience, especially when sharing codes or links.

    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(() => {
            console.log('Text copied to clipboard!');
        }).catch(err => {
            console.error('Failed to copy: ', err);
        });
    }

    copyToClipboard("Hello, World!");

Enter fullscreen mode Exit fullscreen mode

16) File Size Formatter

Formatting file sizes into a human-readable string (e.g., “505K”, “15Mb”, “1.5Gb”) is common in file upload/download scenarios.

    function formatFileSize(size) {
        const units = ['B', 'KB', 'MB', 'GB', 'TB'];
        const index = Math.floor(Math.log(size) / Math.log(1024));
        const formattedSize = (size / Math.pow(1024, index)).toFixed(2);
        return `${formattedSize} ${units[index]}`;
    }

    console.log(formatFileSize(505000)); // "493.68 KB"

Enter fullscreen mode Exit fullscreen mode

17) Validate URL

Checking if a URL is valid and determining whether it’s a domain-only, sub-domain, or full URL is essential in web applications.

    function validateURL(url) {
        const regex = /^(https?:\/\/)?(www\.)?([a-zA-Z0-9-]+\.[a-zA-Z]{2,})(\/.*)?$/;
        const match = url.match(regex);
        if (match) {
            const domain = match[3];
            return {
                isValid: true,
                type: match[1] ? 'full' : (match[2] ? 'sub-domain' : 'domain-only'),
                domain: domain
            };
        }
        return { isValid: false };
    }

    console.log(validateURL("https://www.example.com")); // { isValid: true, type: 'full', domain: 'example.com' }
    console.log(validateURL("www.example.com")); // { isValid: true, type: 'domain-only', domain: 'example.com' }
    console.log(validateURL("example.com")); // { isValid: true, type: 'domain-only', domain: 'example.com' }
    console.log(validateURL("invalid-url")); // { isValid: false }

Enter fullscreen mode Exit fullscreen mode

18) Encrypt & Decrypt Strings

Encrypting sensitive data is crucial for security. Here’s how you can encrypt and decrypt strings using the CryptoJS library.

First, make sure to include CryptoJS in your project. You can install it via npm:

    npm install crypto-js
Enter fullscreen mode Exit fullscreen mode

Then, you can use the following functions:

    const CryptoJS = require("crypto-js");

    function encryptString(str, key) {
        return CryptoJS.AES.encrypt(str, key).toString();
    }

    function decryptString(cipherText, key) {
        const bytes = CryptoJS.AES.decrypt(cipherText, key);
        return bytes.toString(CryptoJS.enc.Utf8);
    }

    const secretKey = "mySecretKey";
    const originalText = "Hello, World!";
    const encryptedText = encryptString(originalText, secretKey);
    console.log(encryptedText); // Encrypted string
    console.log(decryptString(encryptedText, secretKey)); // "Hello, World!"

Enter fullscreen mode Exit fullscreen mode

19) Generate UUID (Universally Unique Identifier)

UUIDs are often used to create unique identifiers for database entries, sessions, and other applications where uniqueness is required.

    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    console.log(generateUUID()); // e.g., "a3bb189e-8bf9-4888-bc14-21c5c6c5381d"

Enter fullscreen mode Exit fullscreen mode

20) Format the Date to a Readable String

Formatting dates into user-friendly strings are common in web applications.

    function formatDate(date) {
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        return new Date(date).toLocaleDateString(undefined, options);
    }

    console.log(formatDate("2024-10-07")); // "October 7, 2024"

Enter fullscreen mode Exit fullscreen mode

These methods are very useful while building an application using JavaScript. I have shared these custom string methods that help me build things faster and provide a more user-friendly experience.

If you have such a list of string manipulation, share it in the comment box. I’ll be happy to explore more options.

Top comments (0)