首页 > 解决方案 > 使用 Javascript 正则表达式将匹配的文本移动到字符串的末尾

问题描述

hello bye!
goodbye again.

我希望将bye上面文本中的任何出现移到最后。我不确定它是否可以通过 Javascript 中的正则表达式来完成。

我希望输出文本是:

hello !
good again.
bye
bye

标签: javascriptregex

解决方案


您可以使用替换加入

  • 首先用空字符串替换匹配的单词
  • 在替换函数的回调中,将值推送到一个数组并从中返回空字符串。
  • 最后加入替换字符串和数组元素\n

let str = `hello bye!
goodbye again.`

let replacer = (str) => {
  let temp = []
  let strTemp = str.replace(/bye/g, match => {
    temp.push(match)
    return ''
  })
  return [strTemp, ...temp].join('\n')
}

console.log(replacer(str))


推荐阅读