[JavaScript]Removing and Replacing Unwanted Characters Using Regular Expressions

目次

Overview

Removing hyphens or spaces from user input and formatting data is an essential skill in web form development. The JavaScript replace() method, when combined with Regular Expressions (RegExp), allows you to replace all occurrences of a specific character throughout a string, rather than just the first one. This article explains how to replace parts of a string and the technique for bulk replacement using the g (global) flag.

Specifications (Input/Output)

  • Input: A product serial code containing hyphens (e.g., PRD-2026-X99).
  • Output: A string with all hyphens removed (e.g., PRD2026X99).
  • Operation:
    • Read the value from an input form when a button is clicked.
    • Delete all hyphens within the string (replace them with an empty string).
    • Display the result on the screen.

Basic Usage

When you provide a string as the first argument to replace(), only the first match is replaced. If you provide a regular expression with the global flag (/pattern/g), every match is replaced.

const rawText = "A-B-C";

// String argument: Only the first "-" found is removed
console.log(rawText.replace("-", "")); 
// Result: "AB-C"

// Regex argument (g flag): All "-" characters are removed
console.log(rawText.replace(/-/g, "")); 
// Result: "ABC"

Full Code (HTML / JavaScript)

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>String Replace Example</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"] { padding: 8px; width: 100%; max-width: 300px; font-family: monospace; }
        button { padding: 8px 16px; background-color: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; }
        button:hover { background-color: #0056b3; }
        .result-box { margin-top: 20px; padding: 10px; background-color: #f4f4f4; border-left: 5px solid #333; }
    </style>
</head>
<body>

    <div class="form-group">
        <label for="serialInput">Product Serial Code (Example: ABCD-1234-EFGH)</label>
        <input type="text" id="serialInput" value="ABCD-1234-EFGH">
    </div>

    <button id="formatBtn">Format String</button>

    <div id="resultArea" class="result-box">Results will appear here</div>

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

JavaScript (app.js)

/**
 * Get references to HTML elements
 */
const serialInput = document.querySelector("#serialInput");
const formatBtn = document.querySelector("#formatBtn");
const resultArea = document.querySelector("#resultArea");

/**
 * Execution logic for formatting
 * @param {Event} event 
 */
const handleFormat = (event) => {
    // Prevent page reload if inside a form
    event.preventDefault();

    // Get the input value
    const originalCode = serialInput.value;

    if (!originalCode) {
        resultArea.textContent = "Please enter a value.";
        return;
    }

    // Replace all hyphens (-) with empty strings to remove them
    // Uses the regex /-/g
    const formattedCode = originalCode.replace(/-/g, "");

    // Display the results
    resultArea.innerHTML = `
        <strong>Before:</strong> ${originalCode}<br>
        <strong>After:</strong> ${formattedCode}
    `;
    
    console.log(`Conversion complete: ${formattedCode}`);
};

// Register the click event
formatBtn.addEventListener("click", handleFormat);

Customization Tips

  • Removing Spaces: To remove both hyphens and spaces, change the regular expression to /[-\s]/g. The \s represents any whitespace character (spaces, tabs, etc.).JavaScript// Remove all hyphens and whitespace const cleanText = text.replace(/[-\s]/g, "");
  • Modern Approach (replaceAll): In environments using ES2021 or later, you can use replaceAll("-", "") to replace all occurrences without using regular expressions. This is useful when prioritizing readability.

Important Notes

  • Original Strings Remain Unchanged: Strings in JavaScript are immutable. Running text.replace(...) does not modify the content of the text variable. You must always assign the return value to a new variable.
  • Special Regex Characters: If you want to replace symbols like . * + or ?, you must escape them with a backslash \ (e.g., replace(/\./g, "")).
  • Full-width Hyphens: Depending on user keyboard input, full-width hyphens () or long dash marks () might be used instead of the standard hyphen (-). To cover these, you need a strict regex like /[-\u30FC\uFF0D]/g.

Advanced Applications

Removing Newline Codes

This example shows how to remove newlines (\n) from text entered in a textarea to create a single line of text.

const textAreaValue = "Line One\nLine Two\nLine Three";

// Replace all newline codes (\n) with empty strings
// Use a pattern that targets \r\n, \n, and \r for different systems
const singleLineText = textAreaValue.replace(/[\r\n]+/g, "");

console.log(singleLineText); // "Line OneLine TwoLine Three"

Conclusion

To replace “all” occurrences of a specific character, the standard method has traditionally been replace(/pattern/g, ""). While replaceAll() is now an option, regular expressions remain a powerful tool because they allow you to specify complex conditions, such as “hyphens or spaces.” Choose the method that best fits your specific requirements.

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

この記事を書いた人

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

目次