Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
557. Reverse Words in a String III javascript (spacing issue)

I'm solving a problem (leetcode 557) Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

When I write the solution below this way I get a wrong answer which is not reversed.

var reverseWords = function(s) {
    let separate = s.split("");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join("")
};

But when I write as shown below my answer is accepted

var reverseWords = function(s) {
    let separate = s.split(" ");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join(" ")
};

I am really confused about how the spacing in quotation marks of the second and last line of code is affecting the solution. Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

s.split("") will find every occurrence of an emtpy string, which is literally between every pair of consecutive characters. So it splits the original string into individual characters. The documentation on mdn has a specific mention of this case:

If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters".

s.split(" ") will find every occurrence of a space, which has much fewer occurrences of course, and it will split your original string into words.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!