我正在尝试解析原始推文字符串以匹配@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>');
所以我的问题是:如何获得我的匹配结果,并用一个跨度包装?
答案 0 :(得分:2)
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>
答案 1 :(得分:1)
一个例子:
myString.replace(/(^|)@(\w+)/g, function handleMatch(match) {
return '<span class="mention">' + match + '</span>';
})
.replace(/(^|)#(\w+)/g, function handleMatch(match) {
return '<span class="hash">' + match + '</span>';
});