如何使用正则表达式在字符串中找到@username(How find @username in string using regex)

编程入门 行业动态 更新时间:2024-10-28 00:20:57
如何使用正则表达式在字符串中找到@username(How find @username in string using regex)

如何使用javascript和regex在给定字符串中找到@username并将它们移动到div?

允许的项目:

@username @user_name

不允许的项目:

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

我想把它们包装成div。 我尝试了什么: https : //regex101.com/r/olqjsv/2

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

最满意答案

使用具有特定正则表达式模式的String.prototype.replace()函数的解决方案:

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

console.log(result); 
  
 

$& - 特殊替换模式,指向匹配的子字符串

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

更多推荐

本文发布于:2023-08-03 15:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393507.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何使用   中找到   正则表达式   regex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!