首页 > 解决方案 > 从字符串消息中获取子字符串以推入数组

问题描述

所以基本上我想从一条带有“@”或“#”之类的特殊字符的消息中获取用户,并将其推送到 user_lists,而只有用户没有特殊字符。

我知道使用正则表达式进行匹配,但我在将每个匹配项推送到数组时遇到了麻烦。

const user_lists = []
const sample_message = '@user and #user2 has a challenge of time management'

我的想法是使用包含但它只返回布尔值。请帮忙。

有效用户名:没有空格和特殊字符。只需获取所有以 @ 或 # 开头的用户名

标签: javascriptnode.jsreactjsregexstring

解决方案


尝试使用match()

(?<=@|#)\w+

正则表达式演示

const sample_message = '@user and #user2 has a challenge of time management'

const user_lists = sample_message.match(/(?<=@|#)\w+/g) || []

console.log(user_lists)


推荐阅读