A few days ago I posted a similar question, but I do not quite understand the principle. Are there good resources where the replace function combined with regular expressions is explained?
Anyways, right now I have the following problem: A string which starts with @
should be placed in an link. So @test
should be replaced to <a href="/test"> @test </a>
.
Also, these rules should apply:
/g
behind the regex? This is what I have so far:
value = "is @test";
var text = value.replace(/^.*(@)(\w+).*$/, "<a href='$2'>$1$2</a>");
My output
<a href="test">@test</a>
EDIT: The link is now working. However, the word "is" is missing.
When performing a .replace()
, you need to include all the characters in the RegExp that you wish to replace, preserving the ones you want to keep with parentheses.
var test = 'is @test'; function makeAt(string){ return string.replace(/^.*(@)(\\w+).*$/, "<a href='$2'>$1$2</a>"); } console.log(makeAt(test));
You need to capture the ambient text:
value = "is @test or what";
var text = value.replace(/^(.*)@(\w+)(.*)$/, "$1<a href='$2'>@$2</a>$3");
Or just capture less:
var text = value.replace(/@(\w+)/, "<a href='$1'>@$1</a>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.