AliN11
AliN11

Reputation: 2573

How find @username in string using regex

How to find @username in given string using javascript and regex and move them to a div ?

Allowed Items:

@username
@user_name

Not Allowed Items:

@_username // non alphabetical character at the beginning
@1username // a number at the beginning
@username_ // underscore at the end

I want to wrap them in a div. What i tried: https://regex101.com/r/olqjsv/2

Upvotes: 1

Views: 763

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using String.prototype.replace() function with specific regex pattern:

var str = "@username  @username_   @user_name @1username",
    result = str.replace(/@[a-z]\w+[a-z]\b/gi, "<div>$&</div>");

console.log(result);

$& - special replacement pattern, points to the matched substring

Upvotes: 4

Abd Elfttah Ahmed
Abd Elfttah Ahmed

Reputation: 90

try tihs

(\@username|\@user_name)|\@([a-zA-Z]+)\_\@([a-zA-Z]+)

Upvotes: -1

Related Questions