Trim off '?' from strings in JavaScript

We are required to write a JavaScript function that takes in a string as the only argument. The string is likely to contain question marks (?) in the beginning and the end. The function should trim off all these question marks from the beginning and the end keeping everything else in place.

For example ?

If the input string is ?

const str = '??this is a ? string?';

Then the output should be ?

'this is a ? string'

Method 1: Using Regular Expressions

The simplest approach uses regex to match question marks at the start and end of the string:

const str = '??this is a ? string?';

const trimQuestionMarks = (str) => {
    return str.replace(/^\?+|\?+$/g, '');
};

console.log(trimQuestionMarks(str));
console.log(trimQuestionMarks('???hello world???'));
console.log(trimQuestionMarks('no question marks'));
this is a ? string
hello world
no question marks

Method 2: Using Loop-Based Approach

For more control, you can manually iterate through the string:

const str = '??this is a ? string?';

const specialTrim = (str = '', char = '?') => {
    str = str.trim();
    
    let countChars = orientation => {
        let inner = (orientation == "left") ? str : 
            str.split("").reverse().join("");
        let count = 0;
        
        for (let i = 0, len = inner.length; i < len; i++) {
            if (inner[i] !== char) {
                break;
            }
            count++;
        }
        return (orientation == "left") ? count : (-count);
    };
    
    const condition = typeof char === 'string' && str.indexOf(char) === 0 && str.lastIndexOf(char) === str.length - 1;
    
    if (condition) {
        str = str.slice(countChars("left"), countChars("right")).trim();
    }
    
    return str;
}

console.log(specialTrim(str));
console.log(specialTrim('???test???'));
this is a ? string
test

Method 3: Simple While Loop Solution

A cleaner approach using while loops:

const trimChar = (str, char = '?') => {
    // Remove from beginning
    while (str.length > 0 && str[0] === char) {
        str = str.slice(1);
    }
    
    // Remove from end
    while (str.length > 0 && str[str.length - 1] === char) {
        str = str.slice(0, -1);
    }
    
    return str;
};

const str = '??this is a ? string?';
console.log(trimChar(str));
console.log(trimChar('????only question marks????'));
console.log(trimChar('middle?marks?here'));
this is a ? string
only question marks
middle?marks?here

Comparison

Method Code Length Performance Readability
Regular Expression Short Fast High
Loop-based Long Medium Medium
While Loop Medium Fast High

Conclusion

For trimming specific characters from string ends, regular expressions provide the most concise solution. The while loop approach offers good readability and performance for simple cases.

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

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements