Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

ตัดออก '?' จากสตริงใน 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