Split in Javascript

I want to split a string,

str = "splitMeIfYouCan";

What I want is,

['split','me','if','you','can']

So, first I made it to lowerCase using String.prototype.toLowerCase() then used String.prototype.split(). No doubt, it was a wrong way.
My code:

  var str = "splitMeIfYouCan";
  var splitStr = str.split(/[A-Z]/);
  //then a for loop to make them lower Case

My Output:

[ 'split', 'e', 'f', 'ou', 'an' ]

What .split() did is cut all Upper Case letters. But I need those letters. Do you have any suggestions?

3 Likes

Good to see that you are comfortable with regex, it is the right direction. But rather than split, perhaps String.match() and a regex with capture groups

3 Likes

You could also look at using splice manually to split this into an array. Split cuts out the separating character.

2 Likes

I’m trying but this is what I get so far :sob: ,
Code:

 var splitStr = str.match(/([a-z]+|[A-Z]+)\w+?[a-z]*/g);

Output:

[ 'splitMe', 'If', 'You', 'Can' ]
1 Like

Hi,

Try to exercise with something like that:

/[......][......]+/g

That is simple but take into account, that your string could begin with upper- or lowercase!
Other solutions also exist!

2 Likes

Okay, finally this,

var splitStr = str.match(/([a-z]|[A-Z]+)(\w+?[a-z]*)/g);

Output:

[ 'split', 'Me', 'If', 'You', 'Can' ]
2 Likes

@JeremyLT I still don’t understand, how can I fix it using .splice() :roll_eyes: ?

you will need a loop for using splice.

Try this (sory it is not Clear i write on phone)===>

function tesst (str) {
let strArr = str.split("");
for( let i = 0;  i<strArr.length; i++){
if(strArr[i] == strArr[i].toUpperCase()){
strArr.splice(i , 0, " ");
i++;
}}
return strArr.join("");
}
alert(tesst("canYouSplitMe"))
3 Likes