修剪 '?' 从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 婆婆高寿祝福语大全简短