简体   繁体   中英

Check first character of a word in a string begins with @

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:

  1. The string can only contain one @, which is at the beginning.
  2. If there are more strings, also replace them. I thought you can do this by putting /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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM