-1

In Javascript, I need a function to split a string based on if it's a capital letter.

Example:

string = "KitKat" should return "Kit Kat".

This is simple to do but, Where I am confused with is when there is a string like "IOTOttawa" I want it to return "IOT Ottawa".

If it has subsequent capitals then keep them together except for the last capital.

Something like that, this is what I have:

s = s.replace(/([a-z])([A-Z])/g, '$1 $2');

I tried using regex but maybe there is another way?

Pete
  • 57,112
  • 28
  • 117
  • 166
ousmane784
  • 306
  • 1
  • 17

1 Answers1

1

We can understand a capital letter if there is a small letter after that.

"IOTOttowa".replace(/([A-Z][a-z])/g, ' $1').trim()

That code will work for your statement.

Onurgule
  • 707
  • 8
  • 21
  • Excellent this worked I also forgot to add that some strings may alos include numbers. For example: 'BellWifi5G' should return 'Bell Wifi 5G' – ousmane784 Feb 11 '21 at 17:15
  • @ousmane784 you can use `/([A-Z][a-z]|[0-9][A-Z])/g` for that. Also I'll be happy if you vote my answer and accept the solution. – Onurgule Feb 11 '21 at 18:11