0

I am having a bit of an issue figuring out how to split a String up with whitespaces between words.

Here is my code

let str = "IWantYouToSplitMeUp"; //I want this string to be "I Want You To Split Me Up"
Klaven Jones
  • 35
  • 1
  • 3

1 Answers1

0

No need for split - that will unnecessarily create an intermediate array. Better to use .replace alone.

Match characters that are followed by capital letters, then replace that character with that character plus a space:

let str = "IWantYouToSplitMeUp";
console.log(str.replace(/.(?=[A-Z])/g, '$& '));

Alternatively, match capital letters that aren't at the beginning of the string, and replace with a space plus that capital letter:

let str = "IWantYouToSplitMeUp";
console.log(str.replace(/(?!^)[A-Z]/g, ' $&'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320