How to work with strings in JavaScript?
Hello everyone! I'm working with Node.js and encountered a problem with string processing. I need to implement a function that takes an array of strings and returns a formatted output: join the strings with a comma, but the last element should be separated by the conjunction "and". For example: ['apple', 'banana', 'orange'] → 'apple, banana and orange'.
I tried using Array.prototype.join(', '), but it adds a comma before the last element, whereas I need to replace it with " and". I attempted to write it manually using a for loop with index checking, but the code ends up cumbersome and doesn't handle edge cases (empty array, single element).
Here's my current code:
function formatList(arr) {\n if (arr.length === 0) return '';\n if (arr.length === 1) retu No answers yet.
Log in to leave an answer
Blogs
HTTP Client in Rust: Making Requests the Right Way
Generics in Kotlin: why they are needed and how to use them
Working with Dates and Time in Java: Advanced Techniques and API
How to Write a REST API in PHP in 30 Minutes: A Practical Guide