1

My current code is like this:

var regex = '@([a-z0-9_]+)';
replacedText = replacedText.replace(regex, '<a href="http://blah.com/$1">$1</a>');

However, when I type a sentence like 'hello this is @test!' it doesn't change anything and it still shows in plain text.

Why is this happening?

4

1 回答 1

5

那是因为您已创建regex为字符串。当您将字符串传递给该replace方法时,它不会将其视为正则表达式;它查找要替换的该字符串的文字出现。

改用正则表达式文字:

var regex = /@([a-z0-9_]+)/;
replacedText = replacedText.replace(regex, '<a href="http://blah.com/$1">$1</a>');

或者调用RegExp构造函数:

var regex = new RegExp('@([a-z0-9_]+)');
replacedText = replacedText.replace(regex, '<a href="http://blah.com/$1">$1</a>');

这是一个工作演示

于 2013-10-03T20:15:30.677 回答