0

我正在尝试解析原始推文字符串以匹配@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>');

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

4

2 回答 2

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>
于 2013-04-09T12:26:50.847 回答
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>';
});
于 2013-04-09T12:27:25.383 回答