使用正则表达式在主题标签周围拆分文本

时间:2019-02-17 23:45:07

标签: javascript regex

如果我有一个类似的字符串: this is a #tag in the middle.

我该如何表达正则表达式以将其拆分为:

["this is a", "#tag", "in the middle."]

从本质上讲,我正在寻找一个以#开头的块,直到该行的末尾或下一个空格。

1 个答案:

答案 0 :(得分:0)

捕获split内的组将包含在结果中,因此您可以使用模式\s*(#\S+)\s*

const str = 'this is a #tag in the middle.';
console.log(
  str.split(/\s*(#\S+)\s*/)
)