如何使用 JavaScript 在给定句子中查找大写单词并在大写单词前添加一个字符?


假设,我们有一个包含大写英文字母的字符串,如下所示:

const str = "Connecting to server Connection has been successful We found result";

我们需要编写一个 JavaScript 函数,此函数可以获取一个这样的字符串,并在每个大写字母前的空格前插入一个逗号“,”。

代码如下:

const str = "Connecting to server Connection has been successful We found
result";
const capitaliseNew = str => {
   let newStr = '';
   const regex = new RegExp(/.[A-Z]/g);
   newStr = str.replace(regex, ',$&');
   return newStr;
};
console.log(capitaliseNew(str));

以下是控制台上的输出:

Connecting to server, Connection has been successful, We found result

更新日期:2020-10-09

158 次浏览

开启您的职业生涯

完成课程以获得认证

开始
广告