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