Split by Caps in 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(" ")
)
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"]
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);
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;