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.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
=\\p{Upper}) matches an empty sequence followed by a uppercase letter, and split uses it as a delimiter. See javadoc for more info on Java regexp syntax.
findall() method to split a string on uppercase letters, e.g. re. findall('[a-zA-Z][^A-Z]*', my_str) . The re. findall() method will split the string on uppercase letters and will return a list containing the results.
To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With