JavaScript: 我如何只反转字符串中的单词

JavaScript: How would I reverse ONLY the words in a string

我如何编写一个函数,它接受一个参数,即一个句子,return一个新句子,其中所有单词都颠倒但顺序与原始句子相同?

测试用例:

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

会 return:

"sihT si nuf, yllufepoh."

这是我目前所拥有的,但请注意我无法让句号和逗号留在原地。不知道是面试官打错了还是什么?

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'
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.'

很可能不是万无一失的

试试这个方法:

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.

用于提取空格、逗号和句点的正则表达式。

算法应该是这样的:

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

如果是面试问题,我认为他们更喜欢算法而不是语言的确切语法。

因此,据我所知,您只是将字符串反转,句点和逗号与字符串相关联。我考虑让它工作的方式是获取 Regex 值,用它们的索引删除它们,然后在你完成原始索引时插入。

希望对您有所帮助

不是最好看的代码或最快的代码,但它有效。

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

对于 Codewars 挑战,我使用了与上述类似的解决方案,但包含在我的正则表达式模式中 a 。和其他特殊字符,以确保在每个字符串元素中完全反转。

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('');
      });
}