在 JavaScript 中从字符串中删除"?"
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/16 1:16:17
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

