【问题标题】:Change the order of the given string in a specific way以特定方式更改给定字符串的顺序
【发布时间】:2021-12-06 04:59:45
【问题描述】:

我有一个字符串,例如“12:13:45.123 UTC Sun Oct 17 2021”,我希望将字符串更改为“Sun Oct 17 2021 12:13:45.123 UTC”。

我这样做

str.slice(18)+' '+str.slice(0,17)

.

但问题是 - 我怎样才能避免调用 slice 两次?有没有办法让它更优雅、更高效?

顺便说一句 - 我不想拆分和连接子字符串。

【问题讨论】:

  • 这么小的东西不需要变得“更有效率”。在“效率”几乎成为问题之前,您可能必须处理数十万个这样的值。

标签: javascript node.js string typescript


【解决方案1】:

您可以将replace 与正则表达式一起使用:

const str = '12:13:45.123 UTC Sun Oct 17 2021';

console.log(str.replace(/(.{16}) (.*)/, '$2 $1'));

恕我直言,它更优雅,但根据https://jsbench.me/,您的代码更快。

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 2021-09-20
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 2019-10-30
    相关资源
    最近更新 更多