Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi làm đối số duy nhất. Chuỗi có thể chứa dấu hỏi (?) ở đầu và cuối. Hàm nên loại bỏ tất cả các dấu hỏi này ở đầu và cuối, giữ nguyên phần còn lại.
Ví dụ:
Nếu chuỗi đầu vào là:
const str = '??this is a ? string?';
Thì đầu ra nên là:
const output = 'this is a ? string';
Ví dụ
Dưới đây là mã nguồn:
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));Kết quả
Đầu ra trên console:
this is a ? string