[JavaScript]String Case Conversion and Input Normalization Techniques

目次

Overview

Normalizing text by treating uppercase and lowercase letters (such as “Admin” and “admin”) as the same is essential when comparing user-entered email addresses or filtering search keywords.

This article explains the basic methods for converting string cases and how to implement input validation that ignores case variations.

Specifications (Input/Output)

  • Input: Text entered into a username input field.
  • Output: A warning message if a forbidden string (e.g., “admin”) is included.
  • Operation:
    • Converts the input string to lowercase in real-time for comparison.
    • Displays a warning if “Admin,” “ADMIN,” “AdMiN,” or any other variation is detected.

Basic Usage

The JavaScript String object provides standard methods for case conversion. These methods do not change the original string but return a new, converted string.

MethodMeaningExampleResult
toLowerCase()Convert all to lowercase"TEST".toLowerCase()"test"
toUpperCase()Convert all to uppercase"test".toUpperCase()"TEST"
const email = "User@Example.com";

// Unify to lowercase for easier comparison (Normalization)
console.log(email.toLowerCase()); // "user@example.com"

Full Code Examples

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Case Insensitive Validation</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .input-group { margin-bottom: 15px; }
        input[type="text"] { padding: 8px; width: 100%; max-width: 300px; font-size: 16px; }
        .warning-message {
            color: #d32f2f;
            font-weight: bold;
            font-size: 0.9em;
            margin-top: 5px;
            display: none; 
        }
        .warning-message.visible { display: block; }
    </style>
</head>
<body>

    <div class="input-group">
        <label for="usernameInput">Username Registration (* "admin" is not allowed)</label><br>
        <input type="text" id="usernameInput" placeholder="Enter username...">
        <div id="warningText" class="warning-message">
            Warning: Usernames containing "admin" cannot be used.
        </div>
    </div>

    <script src="app.js"></script>
</body>
</html>

JavaScript (app.js)

/**
 * Get references to HTML elements
 */
const nameInput = document.querySelector('#usernameInput');
const warningMessage = document.querySelector('#warningText');

/**
 * Forbidden keyword setting (defined in lowercase for comparison)
 */
const FORBIDDEN_KEYWORD = 'admin';

/**
 * Function to validate input values
 */
const validateInput = () => {
    // 1. Get the raw input value
    const rawValue = nameInput.value;

    // 2. Normalize the input by converting it to lowercase
    // This ensures "Admin," "ADMIN," and "admin" are all treated as "admin"
    const normalizedValue = rawValue.toLowerCase();

    // 3. Check if the forbidden keyword is included
    const hasForbiddenWord = normalizedValue.includes(FORBIDDEN_KEYWORD);

    // 4. Toggle warning visibility based on the result
    if (hasForbiddenWord) {
        warningMessage.classList.add('visible');
    } else {
        warningMessage.classList.remove('visible');
    }
};

// Execute validation in real-time using the 'input' event
nameInput.addEventListener('input', validateInput);

Customization Tips

  • Supporting Multiple Keywords: You can store forbidden words in an array (e.g., ['admin', 'root', 'master']) and use the some() method to check if any of them are present.
  • Visual Feedback: Besides showing a message, you can improve the UI by highlighting the input border in red when an error occurs.

Important Notes

  • Not a Destructive Change: Running toLowerCase() does not modify the original variable. You must assign the result to a new variable, such as const lower = str.toLowerCase();.
  • Locale Considerations: Some languages, like Turkish, have unique case conversion rules. For applications requiring strict international support, consider using toLocaleLowerCase().
  • Full-width Characters: While these methods primarily target the standard alphabet, many browsers also support converting full-width characters (e.g., “A” to “a”). However, if strict conversion between full-width and half-width is needed, a separate logic is required.

Advanced Applications

Capitalizing Only the First Letter

This is useful for implementing a “Capitalize” feature in JavaScript, similar to the CSS text-transform: capitalize; property.

const capitalize = (str) => {
    if (!str) return '';
    // Capitalize the first character + lowercase the rest
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};

console.log(capitalize("javaSCRIPT")); // "Javascript"

Summary

Normalizing user input to handle variations in case is a vital step in search features and validation. By using toLowerCase() or toUpperCase() to unify data formats, you can keep your comparison logic simple and build robust applications that prevent unexpected mismatch bugs.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次