Advertisement
satishfrontenddev4

Untitled

Feb 17th, 2024 (edited)
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sure, you can achieve this by splitting the string into words, reversing the order of the words, and then joining them back together. Here's a JavaScript function to do that without using any built-in functions:
  2.  
  3. ```javascript
  4. function reverseWords(str) {
  5.    let reversedStr = ''; // Initialize an empty string to store the reversed string
  6.    let word = ''; // Initialize an empty string to store each word temporarily
  7.    let words = []; // Array to store all the words
  8.    
  9.    // Loop through each character in the string
  10.    for (let i = 0; i < str.length; i++) {
  11.        // If the character is not a space, add it to the temporary word string
  12.        if (str[i] !== ' ') {
  13.            word += str[i];
  14.        } else {
  15.            // If the character is a space, push the temporary word to the array and reset the word string
  16.            words.push(word);
  17.            word = '';
  18.        }
  19.    }
  20.    // Push the last word to the array
  21.    words.push(word);
  22.    
  23.    // Loop through the array of words in reverse order and concatenate them to form the reversed string
  24.    for (let j = words.length - 1; j >= 0; j--) {
  25.        reversedStr += words[j];
  26.        // Add a space between words except for the last word
  27.        if (j !== 0) {
  28.            reversedStr += ' ';
  29.        }
  30.    }
  31.    
  32.    return reversedStr;
  33. }
  34.  
  35. // Example usage:
  36. const inputString = "Sky is the limit";
  37. console.log(reverseWords(inputString)); // Output: "limit the is Sky"
  38. ```
  39.  
  40. This function iterates through the characters of the input string, builds each word, stores them in an array, then constructs the reversed string by concatenating words in reverse order.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement