Split by Caps in Javascript

JavascriptRegexSplit

Javascript Problem Overview


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:

str.split("(?=\\p{Upper})")

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

Javascript Solutions


Solution 1 - Javascript

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

console.log(
  // -> "Hi My Name Is Bob"
  window.prompt('input string:', "HiMyNameIsBob").split(/(?=[A-Z])/).join(" ")  
)

Solution 2 - Javascript

You can use String.match to split it.

"HiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
// 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.

"helloHiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
// Output
["hello", "Hi", "My", "Name", "Is", "Bob"]

Solution 3 - Javascript

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." console.log(str);

Solution 4 - Javascript

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1294188View Question on Stackoverflow
Solution 1 - JavascriptRob WView Answer on Stackoverflow
Solution 2 - JavascriptShiplu MokaddimView Answer on Stackoverflow
Solution 3 - JavascriptSteView Answer on Stackoverflow
Solution 4 - JavascriptM3ghanaView Answer on Stackoverflow