如何使用 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP