Split by Caps in Javascript

I am trying to split up a string by caps using Javascript,

Examples of what Im trying to do:

"HiMyNameIsBob"  ->   "Hi My Name Is Bob"
"GreetingsFriends" -> "Greetings Friends"

I am aware of the str.split() method, however I am not sure how to make this function work with capital letters.

I've tried:


Unfortunately that doesn't work, any help would be great.



Use RegExp-literals, a look-ahead and [A-Z]:

"HiMyNameIsBob".split(/(?=[A-Z])/).join(" ");  // -> "Hi My Name Is Bob"

You can use String.match to split it.

// output 
// ["Hi", "My", "Name", "Is", "Bob"]

If you have lowercase letters at the beginning it can split that too. If you dont want this behavior just use + instead of * in the pattern.

// Output
["hello", "Hi", "My", "Name", "Is", "Bob"]

The solution for a text which starts from the small letter -

let value = "getMeSomeText";
let newStr = '';
    for (var i = 0; i < value.length; i++) {
      if (value.charAt(i) === value.charAt(i).toUpperCase()) {
        newStr = newStr + ' ' + value.charAt(i)
      } else {
        (i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
    return newStr;

To expand on Rob W's answer.

This takes care of any sentences with abbreviations by checking for preceding lower case characters by adding [a-z], therefore, it doesn't spilt any upper case strings.

// Enter your code description here
 var str = "THISSentenceHasSomeFunkyStuffGoingOn. ABBREVIATIONSAlsoWork.".split(/(?=[A-Z][a-z])/).join(" ");  // -> "THIS Sentence Has Some Funky Stuff Going On. ABBREVIATIONS Also Work."


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.