Trim off '?' from strings in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 −

const output = 'this is a ? string';

Example

Following is the code −

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, -1) === 0;
   if (condition) {
      str = str.slice(countChars("left"), countChars("right")).trim();
   };
   return str;
}
console.log(specialTrim(str));

Output

Following is the output on console −

this is a ? string
raja
Published on 10-Dec-2020 08:26:46
Advertisements