反转一个字符串 [英] Reversing a string

查看:104
本文介绍了反转一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要反转一个字符串,然后我想要反转它中的每个单词。我能够扭转字符串。但无法扭转其中的词语。

I want to reverse a string, then I want to reverse each word in it. I was able to reverse the string. But couldn't reverse words in it.

鉴于Str =你好吗
预期结果=你是怎么回事

Given Str = "how are you" Expected Result = "you are how"

我的代码
var my_str =你好吗;
alert(my_str.split('')。reverse()。join(''));

结果我得到: uoy era woh

如何获得最终结果?

推荐答案

如果您的字符串在单词之间只有1个空格,则其他答案完全正确。

the other answers are entirely correct if your string has only 1 space between words.

如果您有多个单词之间的空格,然后事情有点不同:
以相反的顺序获得单词,重新加入1个空格:

if you have multiple spaces between words, then things are a bit different: to get just the words, in reverse order, rejoined by 1 space:

str.split(/\s+/).reverse().join(" ")

反转整个字符串,仍然有原始空格:

to reverse the entire string, and still have the original whitespace:

str.split(/\b/).reverse().join('')

第一个使用正则表达式,/ \ s + /,以匹配整个空间,而不是单个空格。它用单个空格重新连接单词。

the first one uses a regex, "/\s+/", to match an entire run of spaces, instead of a single space. it rejoins the words with a single space.

第二个使用正则表达式/ \\\ /来分割单词和非单词之间的边界话。由于空格的运行将被保留,它只是用空字符串重新加入。

the second one uses a regex, "/\b/", to just split on the boundaries between words and non-words. since the runs of spaces will be preserved, it just rejoins with an empty string.

这篇关于反转一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆