去掉 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP