如何在 JavaScript 字串中新增字元到每個單詞的開頭?
我們需要編寫一個接受兩個字串的函式,返回一個新的字串,該字串與兩個引數中的第一個字串相同,但將第二個引數新增為每個單詞的字首。
例如 −
Input → ‘hello stranger, how are you’, ‘@@’ Output → ‘@@hello @@stranger, @@how @@are @@you’
如果未提供第二個引數,則將“#”作為預設值。
示例
const str = 'hello stranger, how are you';
const prependString = (str, text = '#') => {
return str
.split(" ")
.map(word => `${text}${word}`)
.join(" ");
};
console.log(prependString(str));
console.log(prependString(str, '43'));輸出
控制檯中的輸出將為 −
#hello #stranger, #how #are #you 43hello 43stranger, 43how 43are 43you
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP