Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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:
- ```javascript
- function reverseWords(str) {
- let reversedStr = ''; // Initialize an empty string to store the reversed string
- let word = ''; // Initialize an empty string to store each word temporarily
- let words = []; // Array to store all the words
- // Loop through each character in the string
- for (let i = 0; i < str.length; i++) {
- // If the character is not a space, add it to the temporary word string
- if (str[i] !== ' ') {
- word += str[i];
- } else {
- // If the character is a space, push the temporary word to the array and reset the word string
- words.push(word);
- word = '';
- }
- }
- // Push the last word to the array
- words.push(word);
- // Loop through the array of words in reverse order and concatenate them to form the reversed string
- for (let j = words.length - 1; j >= 0; j--) {
- reversedStr += words[j];
- // Add a space between words except for the last word
- if (j !== 0) {
- reversedStr += ' ';
- }
- }
- return reversedStr;
- }
- // Example usage:
- const inputString = "Sky is the limit";
- console.log(reverseWords(inputString)); // Output: "limit the is Sky"
- ```
- 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