如何在 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

更新於: 20-Aug-2020

810 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.