如何在不反转标点的情况下反转字符串? [英] How to reverse a string in place without reversing the punctuation?

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

问题描述

我正在尝试反转字符串中的单词,而对标点符号没有任何影响.
这是我当前的代码:

I am trying to reverse the words in a string without any effect on punctuation.
This is my current code:

function reverse(str) {
    str = str.split("").reverse().join("");
    str = str.split(" ").reverse().join(" ");
    console.log(str)
}; 

reverse("This is fun, hopefully.")

上述功能的结果为 sihT si,nuf .yllufepoh
而我试图像 sihT si nuf,yllufepoh那样得到它.

推荐答案

另一种方法是使用 replace 和正则表达式(例如

Another approach is to replace all sequences of letters with their reversed forms using replace and a regular expression, e.g.

function reverseWords(s) {
  return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}

document.write(reverseWords("This is fun, hopefully.")); // sihT si nuf, yllufepoh. 

如果您希望包含数字作为单词字符(例如W3C),则正则表达式应为:

If you wish to include numbers as word characters (w.g. W3C), then the regular expression should be:

/\ w +/g

这篇关于如何在不反转标点的情况下反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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