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,我想知道这是什么问题
答案 0 :(得分:1)
你需要按空格分割字符串
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"))
&#13;
答案 1 :(得分:0)
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
答案 2 :(得分: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"));
答案 3 :(得分:0)
此功能适用于您:
function myFunction(string) {
return string.split("").reverse().join("").split(" ").reverse().join(" ")
};
答案 4 :(得分:0)
如果您看起来像这样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
答案 5 :(得分: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));
答案 6 :(得分: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
答案 7 :(得分: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);