Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Split string on UpperCase Characters

Tags:

javascript

People also ask

How to split a string by capital letters JavaScript?

Split a String on Capital Letters in JavaScript # To split a string on capital letters, call the split() method with the following regular expression - /(? =[A-Z])/ . The regular expression uses a positive lookahead assertion to split the string on each capital letter and return an array of the substrings.

How do you capitalize in JavaScript?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize the first letter of each word in a string in JavaScript?

In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase. For instance: const publication = "freeCodeCamp"; publication[0].


I would do this with .match() like this:

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g);

it will make an array like this:

['This', 'Is', 'The', 'String', 'To', 'Split']

edit: since the string.split() method also supports regex it can be achieved like this

'ThisIsTheStringToSplit'.split(/(?=[A-Z])/); // positive lookahead to keep the capital letters

that will also solve the problem from the comment:

"thisIsATrickyOne".split(/(?=[A-Z])/);

.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

This should handle the numbers as well.. the join at the end results in concatenating all the array items to a sentence if that's what you looking for

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

Output

"This Is The String To Split"

Here you are :)

var arr = UpperCaseArray("ThisIsTheStringToSplit");

function UpperCaseArray(input) {
    var result = input.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
    return result.split(",");
}

This is my solution which is fast, cross-platform, not encoding dependent, and can be written in any language easily without dependencies.

var s1 = "ThisЭтотΨόυτÜimunəՕրինակPříkladדוגמאΠαράδειγμαÉlda";
s2 = s1.toLowerCase();
result="";
for(i=0; i<s1.length; i++)
{
 if(s1[i]!==s2[i]) result = result +' ' +s1[i];
 else result = result + s2[i];
}
result.split(' ');