문자열을 유일한 인수로 취하는 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