修剪 '?' 从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 新年送老师简短祝福语
11 爱小姨文案祝福语简短
12 开业经典祝福语简短
13 哥哥祝福语简短霸气句子
14 古风婚礼祝福语唯美简短
15 新年留言老师祝福语简短
16 祝福语简短七夕
17 朋友药店开业祝福语简短
18 毕业创意蛋糕祝福语简短