如何使用 JavaScript 在给定的句子中查找大写单词并在其前面添加一个字符?
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/16 17:16:17
假设我们有一个字符串,其中包含一些大写英文字母,例如 −
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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

