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"]