How to find capitalized words and add a character before that in a given sentence using JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Updated on 09-Oct-2020 11:24:21

Advertisements