去掉 JavaScript 中字串中的“?”


我們需要編寫一個 JavaScript 函式,該函式僅將一個字串作為其引數。此字串的開頭和結尾可能包含問號 (?)。該函式應當移除開頭和結尾處的所有這些問號,同時保持其他內容不變。

例如 −

如果輸入字串為 −

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

那麼輸出應為 −

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

輸出

以下是控制檯上的輸出 −

this is a ? string

更新日期: 10-12-2020

79 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.