admin管理员组

文章数量:1287949

How would i write a function that takes one argument that is a sentence and returns a new sentence where all words are reversed but kept in the same order as the original sentence?

Test Case:

wordsReverser("This is fun, hopefully.");

Would return:

"sihT si nuf, yllufepoh."

This is what I have so far but notice that I cant get the period and ma to stay in place. I don't know if this was a typo by the interviewer or what?

function wordsReverser(str){
  return str.split(' ').
    map(function(item) {    
        return item.split('').reverse().join('');
    }).join(' ');
}

wordsReverser("This is fun, hopefully.");
//Output: 'sihT si ,nuf .yllufepoh'

How would i write a function that takes one argument that is a sentence and returns a new sentence where all words are reversed but kept in the same order as the original sentence?

Test Case:

wordsReverser("This is fun, hopefully.");

Would return:

"sihT si nuf, yllufepoh."

This is what I have so far but notice that I cant get the period and ma to stay in place. I don't know if this was a typo by the interviewer or what?

function wordsReverser(str){
  return str.split(' ').
    map(function(item) {    
        return item.split('').reverse().join('');
    }).join(' ');
}

wordsReverser("This is fun, hopefully.");
//Output: 'sihT si ,nuf .yllufepoh'
Share Improve this question edited Aug 5, 2022 at 23:07 philipxy 15.2k6 gold badges42 silver badges97 bronze badges asked Dec 16, 2015 at 0:01 hackermannhackermann 1292 silver badges6 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 3

Try this way:

function wordsReverser(str){
  return str.replace(/[a-zA-Z]+/gm, function(item) {    
        return item.split('').reverse().join('');
    });
}

wordsReverser("This is fun, hopefully.");
//Output: 'sihT si nuf, yllufepoh.'

How It Works: the replace() function will find each word and pass to the function which will reverse the word (the function returns the reverse word which replaces the word in the string) and all other should remain as that was before.

function wordsReverser(str){
  return str.split(/(\s|,|\.)/).
    map(function(item) {    
        return item.split('').reverse().join('');
    }).join('');
}

wordsReverser("This is fun, hopefully.");
// Output: sihT si nuf, yllufepoh.

Regex to extract whitespace, mas and periods.

function wordsReverser(str){
  return str.split(' ').
    map(function(item) {    
        var letters = item.match(/[a-z]*/i);
    return item.replace(letters[0], letters[0].split('').reverse().join(''));
}).join(' ');

}

 wordsReverser("This is fun, hopefully.");
//Output: 'sihT si nuf, yllufepoh.'

Most likely not fool proof

The algorithm would be something like this:

placeholder_array = [];
  result = '';
  foreach char in inputstring
    if(char !=',' || char != '.'){
         add char to placeholder_array;
    }
    else{
         result = result + reverse of placeholder_array
         placeholder_array = []
    }

   result = result + reverse of placeholder_array

If it's an interview question, I think they'd like more like an algorithm than exact syntax of the language.

So, from what I see you are just reversing the string, the period and ma are associated with the string. The way I am thinking about making it work is grabbing the Regex values, removing them with their index, then insert when youre done at the original index.

Hope this helps

Not the best looking code or the fastest, but it works.

solve = (sentence) => sentence.split('').reverse().join('').split(' ').map(el => el.split('').join('')).reverse().join(' ');

For the Codewars challenge, I used a similar solution to the above, however included in my regex pattern a . and other special characters to ensure that there would be a total reverse in each string element.

function reverseWords(str){
    //Using replace, we can pass a regex object or literal pattern.
    //We pass this to a function as the second parameter
    //The functions return value will be used as the replacement string
    return str.replace(/[$&+,:;=?@#|'<>.^*()%!-|a-zA-Z]+/gm, function(item) {    
          return item.split('').reverse().join('');
      });
}

function reverse(string) {
  let data = string.match(/[a-zA-Z]+/g).join("");
  data = data.split("").reverse().join("");
  let index = 0;
  let result = "";
  for (let i of string.split("")) {
    if (i.match(/[a-zA-Z]/)) {
      result += data[index];
      index += 1;
    } else {
      result += i;
    }
  }
  return result;
}

console.log(reverse("a-bcd-ef-ghi--jkl-m!!"));

reverse only alphabet in a string in which some special characters exist and also some digits exists but its reverse only alphabet characters

let string = "2i3u42idospo233!@kl!@#iio%%^hh^GFG&JK&";

function reverse(string) {
  let match = string.match(/[a-zA-Z]/gi).reverse();
  for (let i = 0; i < string.length; i++) {
    if (!string[i].match(/[a-zA-Z]/)) {
      match.splice(i, 0, string[i]);
    }
  }
  return match.join("");
}

console.log(reverse(string));

本文标签: JavaScript How would I reverse ONLY the words in a stringStack Overflow