Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - Convert a string to all-lowercase-words-joined-by-dashes

function spinalCase(str) {
      for ( var i = 0; i < str.length; i++) {
          if ( i == 0 && /[A-Z]/.test(str[i]) ) {
              str.replace(str[i], str[i].toLowerCase()) }
          else if ( i !== 0 && /[A-Z]/.test(str[i])) {
              str.replace(str[i], " " + str[i].toLowerCase()); } }
      return str.replace(/s+/ig, "-");
}

I have passed this test actually, but I still don't understand what did I miss here. Can somebody help me?

Many thanks

question from:https://stackoverflow.com/questions/66061998/convert-a-string-to-all-lowercase-words-joined-by-dashes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For why the code "passed this test actually" I have no answer - the test code must be defective.

What has been missed is that the string.replace method returns a new string with a replacement made if a match for the first argument string was found, or an unmodified copy of the original string if no match was found. The string on which replace is called remains unchanged.

So, while the str.replace() calls may replace characters, the updated string returned by the call is not captured.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...