0

How do i make it so the function will take in the param (breed) and search the uppercase letter and add a space there.

for example if i pass "goldenRetriever" as the param, then the function will transform it into "golden retriever"

function test(breed){
    for(i=1; i<breed.length; i++){
    //wat do i do here
    }
}
  • This smells so much like a homework assignment to me. Try searching, I'll start you off with the first solution: http://stackoverflow.com/questions/1027224/how-can-i-test-if-a-letter-in-a-string-is-uppercase-or-lowercase-using-javascrip – Duniyadnd Feb 19 '16 at 02:34
  • I wouldn't use a loop when .replace() with a regular expression can do it. – nnnnnn Feb 19 '16 at 02:36

1 Answers1

5

You could split the string before each uppercase letter using a regular expression with a positive lookahead, /(?=[A-Z])/, then you could join the string back together with a space and convert it to lowercase:

"goldenRetrieverDog".split(/(?=[A-Z])/).join(' ').toLowerCase();
// "golden retriever dog"

Alternatively, you could also use the .replace() method to add a space before each capital letter and then convert the string to lowercase:

"goldenRetrieverDog".replace(/([A-Z])/g, " $1").toLowerCase();
// "golden retriever dog"
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • @Firefalcon1155 Because you're not returning the string. It should be `return breed.split(/(?=[A-Z])/).join(' ').toLowerCase();`.. see this example -> https://jsfiddle.net/L7m2x7uL/ – Josh Crozier Feb 19 '16 at 02:58