如何使用 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 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.