去掉 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