reverse words in a string javascript code example

Example 1: javascript reverse a string

function reverseString(s){
    return s.split("").reverse().join("");
}
reverseString("Hello");//"olleH"

Example 2: reverse words in a string javascript

function reverseString(str) {
    return str.split("").reverse().join("");
}
reverseString("hello");

Example 3: javascript how to reverse a string

function reverseString(str) {
    // Step 1. Use the split() method to return a new array
    var splitString = str.split(""); // var splitString = "hello".split("");
    // ["h", "e", "l", "l", "o"]
 
    // Step 2. Use the reverse() method to reverse the new created array
    var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
    // ["o", "l", "l", "e", "h"]
 
    // Step 3. Use the join() method to join all elements of the array into a string
    var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
    // "olleh"
    
    //Step 4. Return the reversed string
    return joinArray; // "olleh"
}
 
reverseString("hello");

Example 4: reverse words javascript

function reverseInPlace(str) {
  var words = [];
  words = str.match(/\S+/g);
  var result = "";
  for (var i = 0; i < words.length; i++) {
     result += words[i].split('').reverse().join('') + " ";
  }
  return result
}
console.log(reverseInPlace("abd fhe kdj"))

Example 5: reverse words javascript

function reverse (word) {
    word = word.split('.').reverse().join('.')
    return word

}
word = 'i.like.this.program.very.much'
word = 'pqr.mno'
console.log(reverse(word))

Example 6: reverse a word javascript

function reverseWords(str) {
  const allWords = str.split(" ")
  return allWords.map(item => item.split("").reverse().join("")).join(" ")
}

Tags:

Misc Example