Suppose, we have a string that contains some capitalized English alphabets like this −
const str = "Connecting to server Connection has been successful We found result";
We are required to write a JavaScript function that takes in one such string and inserts a comma ',' before the space before every capital letter in the string.
The code for this will be −
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));
Following is the output on console −
Connecting to server, Connection has been successful, We found result