-1

how to get this on javascript? given a name with no spaces AndrewGonzalezPuerta convert into this Andrew Gonzalez Puerta

Insert a space before every capital letter not counting the first one

Sergi
  • 743
  • 1
  • 9
  • 17

1 Answers1

2

Here's a regex solution using a lookahead to make sure that the capital letter is not at the beginning of the string.

const name = "AndrewGonzalezPuerta";

console.log(name.replace(/(?!^)([A-Z])/g, " $1"));
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • `SyntaxError: Invalid regular expression: invalid` – Mark Aug 12 '18 at 23:10
  • @MarkMeyer What Browser are you using? – Luca Kiebel Aug 12 '18 at 23:11
  • @Luca I'm using the latest Safari – Mark Aug 12 '18 at 23:11
  • @MarkMeyer Thanks for the word. Can you try it again? – ggorlen Aug 12 '18 at 23:15
  • Yep, that did it @ggorlen. It's working here now. – Mark Aug 12 '18 at 23:17
  • @MarkMeyer Thanks. Do you recommend deleting this since the question has already been answered? – ggorlen Aug 12 '18 at 23:18
  • Honestly, @ggorlen, I'm not sure what the community view is on that. In an ideal world all questions would have one thread, but when I'm searching for something on SO I often find solutions in dupes that are better than the original. So I'm not sure. Might be a good question for https://meta.stackoverflow.com (if it's not already there). – Mark Aug 12 '18 at 23:21