How to sort the words in a string with Node.js

1 Answer

0 votes
function sortTheWordsInAString(s) {
    let arr = s.split(" ");
    
    arr.sort();

    let result = "";
    for (let str of arr) {
        result += str + " ";
    }

    if (result.length > 0) {
        result = result.slice(0, -1); // Remove the last space
    }

    return result;
}

let s = "php c node.js c++ python c#";

s = sortTheWordsInAString(s);

console.log(s);



/*
run:
    
c c# c++ node.js php python
    
*/

 



answered Jul 29, 2024 by avibootz
edited Jul 29, 2024 by avibootz
...