如何反转字符串中的单词而不是反转整个字符串?

问题描述 投票:0回答:16
function reverseInPlace(str) {
    var words = [];
    words = str.split("\s+");
    var result = "";
    for (var i = 0; i < words.length; i++) {
        return result += words[i].split('').reverse().join('');
    }
}
console.log(reverseInPlace("abd fhe kdj"))

我所期望的是

dba ehf jdk
,而我在这里得到的是
jdk fhe dba
。有什么问题吗?

javascript string reverse in-place
16个回答
9
投票

此功能应该适合您:

function myFunction(string) {
    return string.split("").reverse().join("").split(" ").reverse().join(" ")
};

6
投票

您需要按空格分割字符串

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"))


4
投票

Split
先将字符串转换为单词,然后再反转各个单词

var input = "abd fhe kdj";
var output = input.split( " " ).map(  //split into words and iterate via map
     s => s.split("").reverse().join( "" )  //split individual words into characters and then reverse the array of character and join it back
).join( " " ); //join the individual words

1
投票

如果你看起来像这样的o/p:“Javascript is Best”=>“Best is Javascript”

然后通过简单的逻辑就可以完成

//sample string
     let str1 = "Javascript is Best";
//breaking into array
     let str1WordArr = str1.split(" ");
//temp array to hold the reverse string      
      let reverseWord=[];
//can iterate the loop backward      
     for(let i=(str1WordArr.length)-1;i>=0;i--)
     {
//pushing the reverse of words into new array
          reverseWord.push(str1WordArr[i]); 
     }
//join the words array 
      console.log(reverseWord.join(" ")); //Best is Javascript

1
投票

const reverseWordIntoString = str => str.split(" ").map(word => word.split("").reverse().join('')).join(" ")

const longString = "My name is Vivekanand Panda";
const sentence = "I love to code";


const output = {
  [longString]: reverseWordIntoString(longString),
  [sentence]: reverseWordIntoString(sentence)
}

console.log(output);


0
投票

您可以利用

split
map
功能来创建相反的单词。

您需要首先使用

sentence
拆分
space
,然后您可以反转每个单词并再次连接反转的单词。

function reverseWord (sentence) {
  return sentence.split(' ').map(function(word) {
    return word.split('').reverse().join('');
  }).join(' ');
}

console.log(reverseWord("abd fhe kdj"));


0
投票

此解决方案保留空白字符空格

,制表符
\t
,新行
\n
和回车
\r
)并保留它们的顺序(不颠倒):

const sentence = "abd\t fhe kdj";

function reverseWords(sentence) {
    return sentence
        .split(/(\s+)/)
        .map(word => /^\s+$/.test(word) ? word : word.split('').reverse().join(''))
        .join('');
}

console.log(reverseWords(sentence));


0
投票
If you want to reverse a string by word:
Example: 'Welcome to JavaScript' to 'JavaScript to Welcome'

You can also do something like:
var str = 'Welcome to JavaScript'
function reverseByWord(s){
  return s.split(" ").reverse().join(" ");
}

// Note: There is space in split() and Join() method

reverseByWord(str)
// output will be - JavaScript to Welcome

0
投票

您可以通过以下代码轻松实现

function reverseWords(str) {
    // Go for it
    let reversed;
    let newArray=[];
    reversed = str.split(" ");
    for(var i = 0;i<reversed.length; i++)
    {
        newArray.push(reversed[i].split("").reverse().join(""));       
    }
    return newArray.join(" ");
}
let reversedString = reverseWords("This is an example!");
console.log("This is the reversed string : ",reversedString);


0
投票

唯一的错误是在进行分割时你可以这样做:

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

0
投票

let s = “getting good at coding needs a lot of practice”
let b = s.split(" ").reverse().join(" ")

console.log(b)
 


0
投票

-> 将字符串拆分为单词数组

str.split(" ")
-> 映射每个单词并拆分为每个字符
.map(word => word.split("")
-> 单独反转每个单词并连接它

.map(word => word.split("").reverse().join("")

const str = "abd fhe kdj";

const reverseWord = str => {
  let reversed = "";
  reversed = str.split(" ").map(word => word.split("").reverse().join("")).join(" ")
  
  
  return reversed
}

console.log(reverseWord(str));


0
投票

对于现在研究这个问题的人来说,想想你的应用程序是否不需要处理标点符号(例如不移动标点符号)或翻转连字符(例如签入应该是 ni-kcehc 或 kcehc-ni ?) .

例如:

  • “无知就是幸福?!”真的应该是“ecnarongi si !?ssilb”吗?
  • “旋转木马”应该是“dnuor-og-yrreM”或“yrreM-og-dnuor”?

以下解决方案不会移动标点符号,也不会翻转连字符的单词:

/**
* 1. Split "non letters"
* 2. Reverse each piece
* 3. Join the pieces again, replacing them by " "
* 4. Split all characters
* 5. Replace " " by the original text char
*/

function reverseWords(text) {
    return text.split(/[^A-Za-zÀ-ÿ]/g)
        .map(w => w.split("").reverse().join(""))
        .join(" ")
        .split("")
        .map((char, i) => char === " " ? text[i] : char)
        .join("")
}

0
投票
function reverse(str) {
    var rev = str.split("").map(word => word.split("").reverse().join("")).join(" ")
    return rev
}

console.log(reverse("soumya prakash")); // aymuos hsakarp

0
投票

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"))


0
投票
reverseStringBywords = (str) =>{
  let rev = ""
  str.split(" ").forEach(s =>{ 
      rev = rev + s.split("").reverse().join("") + " " 
  })
  return  rev
}
console.log("reverseStringBywords ", reverseByWord("JavaScript is awesome"));
© www.soinside.com 2019 - 2024. All rights reserved.