Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

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

like image 952
user1294188 Avatar asked Apr 08 '12 17:04

user1294188


People also ask

How do you split an element in JavaScript?

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.

How do you separate lowercase and uppercase in Java?

=\\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.

How do you split a string into capital letters in python?

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.

How do you capitalize first letter?

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.


2 Answers

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(" ")   )
like image 50
Rob W Avatar answered Sep 18 '22 21:09

Rob W


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"] 
like image 38
Shiplu Mokaddim Avatar answered Sep 21 '22 21:09

Shiplu Mokaddim