-3

I want find special character like @ from the string and wrap it to html tag like span or div, like var str = "@user you email id is some@gmail.com".

So i want @user to be <span class="class">@user</span>, but the email should not be effected as it also have @,

I am new to regex, but came up with an regex but it doesn't work /\@[\w]+/g but this also selects the @gmail from the email, which is incorrect, Please help

Tapan Dave
  • 37
  • 7

2 Answers2

0

Simply use template strings

str = `<span>@user</span> you email id is some@gmail.com`

No need regex here.

Edit : With regex to get @user try this \B@\w+

Sephyre
  • 326
  • 2
  • 13
  • 1
    i want it from the string and the string is dynamic , please read the question properly – Tapan Dave Sep 29 '20 at 06:08
  • I would suggest bro to add atleast default string after the first `@` so it would be easier for you to identify the first `@` without affecting the emailaddress. – MONSTEEEER Sep 29 '20 at 06:19
0

Use \B to make sure there isn't a word boundary right in front of @.

const str = "@user you email @id is some@gmail.com";
str.replace(/\B(\@\w+)/g, '<span>$1</span>');

Result:

"<span>@user</span> you email <span>@id</span> is some@gmail.com"
Bill
  • 764
  • 6
  • 14