如何從字串中獲取奇數和偶數位置的字元?
我們必須編寫一個函式,該函式從字串中移除每第二個字元(從第一個字元開始),並將所有這些被移除的字元追加到 JavaScript 的末尾。
例如 −
If the string is "This is a test!" Then it should become "hsi etTi sats!"
因此,讓我們編寫此函式的程式碼 −
示例
const string = 'This is a test!';
const separateString = (str) => {
const { first, second } = [...str].reduce((acc, val, ind) => {
const { first, second } = acc;
return {
first: ind % 2 === 1 ? first+val : first,
second: ind % 2 === 0 ? second+val : second
};
}, {
first: '',
second: ''
})
return first+second;
};
console.log(separateString(string));輸出
控制檯中的輸出將為 −
hsi etTi sats!
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP