如何在 JavaScript 中向字符串中每个单词的开头添加一个字符?
javascriptweb developmentobject oriented programming更新于 2025/9/29 18:52:17
我们需要编写一个接受两个字符串的函数,我们必须返回一个新字符串,该字符串与两个参数中的第一个相同,但第二个参数添加到其每个单词的前面。
例如 −
输入 → ‘hello stranger, how are you’, ‘@@’ 输出 → ‘@@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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

