Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thêm ký tự vào đầu mỗi từ trong chuỗi JavaScript

Viết hàm nhận 2 chuỗi, trả chuỗi mới với chuỗi thứ 2 thêm vào đầu mỗi từ của chuỗi 1.

Ví dụ:

Input → 'hello stranger, how are you', '@@' Output → '@@hello @@stranger, @@how @@are @@you'

Mặc định thêm '#'.

Ví dụ

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'));

Kết quả

Đầu ra console:

#hello #stranger, #how #are #you 43hello 43stranger, 43how 43are 43you