Implement polyfill for String.prototype.trim() method in JavaScript

Some old versions of browsers don't support newly evolved JavaScript features. For example, very old browser versions don't support ES10 features like the Array.flat() method for flattening arrays.

In such cases, we need to implement user-defined methods called polyfills to provide that functionality for older browsers. Here, we will implement polyfills for the String.prototype.trim() method.

What is String.prototype.trim()?

The trim() method removes whitespace characters from both ends of a string and returns a new string without modifying the original.

Method 1: Using Regular Expression

The most common approach uses a regular expression to match and replace whitespace:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

Regular Expression Breakdown

  • ^ ? Start of the string

  • \s+ ? One or more whitespace characters

  • | ? OR operator

  • \s+$ ? One or more whitespace characters at the end

  • g ? Global flag to replace all matches

Example: Built-in trim() Method

<html>
<body>
    <h2>Using the built-in trim() method</h2> 
    <div id="content"></div>
    <script>
        let content = document.getElementById('content');
        let str = "   This is a string with white spaces!   ";
        content.innerHTML += "Original string: '" + str + "'<br>";
        let trimmed = str.trim();
        content.innerHTML += "Trimmed string: '" + trimmed + "'<br>";
    </script>
</body>
</html>

Example: Regex-based Polyfill

<html>
<body>
    <h2>Using trim() method with regex polyfill</h2>
    <div id="content"></div>
    <script>
        let content = document.getElementById('content');
        
        // Polyfill implementation
        if (!String.prototype.trim) {
            String.prototype.trim = function() {
                return this.replace(/^\s+|\s+$/g, "");
            }
        }
        
        let str = "   Hi, How are you?   ";
        content.innerHTML += "Original string: '" + str + "'<br>";
        let trimmed = str.trim();
        content.innerHTML += "Trimmed string: '" + trimmed + "'<br>";
    </script>
</body>
</html>

Method 2: Manual Character Iteration

This approach manually finds the first and last non-whitespace characters using loops:

<html>
<body>
    <h2>Using trim() method with manual iteration polyfill</h2>
    <div id="content"></div>
    <script>
        let content = document.getElementById('content');
        
        String.prototype.trim = function() {
            const spaces = [" ", "\t", "<br>", "\r", "\f", "\v"];
            let start = 0;
            let end = this.length - 1;
            
            // Find first non-whitespace character
            for (let i = 0; i < this.length; i++) {
                if (!spaces.includes(this[i])) {
                    start = i;
                    break;
                }
            }
            
            // Find last non-whitespace character
            for (let i = this.length - 1; i >= 0; i--) {
                if (!spaces.includes(this[i])) {
                    end = i;
                    break;
                }
            }
            
            // Return trimmed substring
            return start > end ? "" : this.slice(start, end + 1);
        }
        
        let str = "   Hi, How are you?   ";
        content.innerHTML += "Original string: '" + str + "'<br>";
        let trimmed = str.trim();
        content.innerHTML += "Trimmed string: '" + trimmed + "'<br>";
    </script>
</body>
</html>

Comparison of Methods

Method Performance Code Size Readability
Regular Expression Fast Compact Good
Manual Iteration Slower Longer More verbose

Best Practice: Feature Detection

Always check if the method exists before defining your polyfill:

if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, "");
    }
}

Conclusion

The regular expression approach is recommended for String.prototype.trim() polyfills due to its simplicity and performance. Always use feature detection to avoid overwriting native implementations in modern browsers.

Updated on: 2026-03-15T23:19:00+05:30

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements