1

the logic behind itI have the following code that I made based on an example from MDN.

function spinalCase(str){
 return  str = str.replace(/[A-Z]/g,function(match, offset, string) {
   return (offset > 0 ? '-' : '') + match.toLowerCase();
});          
}

Would someone please explain me how the following line of code works?

return (offset > 0 ? '-' : '') + match.toLowerCase();

I've tried to understand it based on the replace() method page from MDN but so far I don't understand the logic behind it.

What I mostly don't understand is how (offset > 0 ? '-' : '') + match.toLowerCase() returns the word with the replacement. Does the replace function do a loop to iterate through all letters? Or does it just returns the entire ready string with the replacement...

11
  • Which part you don't understand? Are you familiar with ternary operator? Commented Feb 9, 2018 at 22:53
  • Yes, I am, but I don't understand the "offset > 0" part... And how it simply adds the match.toLowerCase() after the ternary part Commented Feb 9, 2018 at 22:55
  • Lets clarify this ternary operator: if offset bigger than 0 then '-' else '' and String concatenation Commented Feb 9, 2018 at 22:57
  • Possible duplicate of How do you use the ? : (conditional) operator in JavaScript? Commented Feb 9, 2018 at 22:57
  • 1
    @Barmar - I guess I need stronger glasses. Commented Feb 9, 2018 at 23:10

1 Answer 1

3

The JS String Replace method can take a function as it's second parameter, which will get passed matches in the input string. Each match gets passed into that inner function, and is replaced in the input string by whatever that inner function returns.

In this case the pattern matches [A-Z] (all capital letters).

So in the string "ThisIsAString" we will match "T", "I", "A", and "S"

The inner function uses a ternary: offset > 0 ? '-' : '' (compact if/else) to prefix a dash if this match is not the first character. It could be reworded as: "if this match is not the first character, prefix with a dash. Otherwise, do not prefix anything."

the last part: + match.toLowerCase() converts the matched character to lowercase, so now our matches will be replaced by: "t", "-i", "-a" and "-s"

Sign up to request clarification or add additional context in comments.

2 Comments

@caio the 'offset' argument of the inner function refers to the match's offset from the start of the string. In my example "T" has an offset of 0 (first char), "I" has an offset of 4 (fifth char) etc
if you want to experiment with the code some more to understand it better, try out your browser's debugger! Here's a crash course in Chrome for example: developers.google.com/web/tools/chrome-devtools/javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.