In this article, we will see how to put space between words that start with capital letters, basically, we use the Regex in javascript.
A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern.
We have an array of characters which is basically a sentence with no difference between words and the first letter of the word is in uppercase. Here we are using replace() method and split() method with Regex to put spaces between words starting with a capital letter. For instance, the below example illustrates the Regex in JavaScript by adding spaces between words starting with capital letters.
Input: GeeksForGeeks Output: neveropen for neveropen
Approach 1: In this approach, we will use replace() method with regex to put space between our sentence and then use toLowerCase() to make all characters lowercase.
Example: In this example, we are using the above-explained approach.
Javascript
// Function to putspace between words // starting with capital letters function PutSpace(str) { // [A-Z] means match only uppercase // letter from A-z // " $&" means put space first and then // Inserts the matched substring let res = str.replace(/([A-Z])/g, ' $&' ) res = res.toLowerCase() console.log(res) } let str1 = "GEEKS@#$786$^neveropen" PutSpace(str1); |
Output:
g e e k s@#$786$^neveropen
Approach 2: In this example, we use Regex with split() to put space in our sentence and then use join() methods to join our array with space at last use toLowerCase() to convert all characters in lower case.
Example: Here we are using the above approach.
Javascript
let myString = "GEEKS@#$786$^neveropen" ; let result = myString.split(/(?=[A-Z])/).join( " " ); console.log(result.toLowerCase()); |
Output:
g e e k s@#$786$^neveropen