javascript - 匹配@username和#topic并将结果包装在span中

标签 javascript regex

我正在尝试解析原始推文字符串以匹配@username和#topic部分,我能够匹配它们,但我不熟悉如何包装它们。

我的代码:

"Hey @someotheruser this is a tweet about #topic1 and #topic1".replace(/(^|)@(\w+)/, '<span class="mention">?result of match?</span>');

"Hey @someotheruser this is a tweet about #topic1 and #topic1".replace(/(^|)#(\w+)/, '<span class="hash">?result of match?</span>');

所以我的问题是:如何获得比赛的结果,并用跨度包裹它?

最佳答案

var my_string = 'Hey @someotheruser this is a tweet about #topic1 and #topic1';

my_string = my_string.replace(/(\@\w+)/g, '<span>$&</span>');
my_string = my_string.replace(/(\#\w+)/g, '<span>$&</span>');

console.log(my_string);

输出

Hey <span>@someotheruser</span> this is a tweet about <span>#topic1</span> and <span>#topic1</span>

关于javascript - 匹配@username和#topic并将结果包装在span中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15901783/

相关文章:

javascript - 样式组件中的多个 Prop 检查

javascript - onload 和 onclick 等效吗?

regex - 如何改变氚变量字符串?

java - 复杂的正则表达式 - 这可能吗?

php - 具有正则表达式字符类的 CDbCriteria 参数

javascript - observableArray 本身及其内部值都有 Push 方法

javascript - 如何删除 FullCalendar 中的 "previous"、 "next"和 "today"按钮

javascript - 将 javascript 日期转换为 json 日期格式

使用正则表达式用四舍五入的数字替换字符串中的数字

java - 在Java中使用正则表达式在给定段落中查找 'wh'句子