修剪 '?' 从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