javascript - 如何使用正则表达式在字符串中查找@username

标签 javascript regex

如何使用 javascript 和正则表达式在给定的字符串中找到 @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

最佳答案

使用 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);

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

关于javascript - 如何使用正则表达式在字符串中查找@username,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42875287/

相关文章:

javascript拆分正则表达式

javascript - Node : Middleware for only page loading

javascript - 在 Rails 中编码图像上传时如何确保正确的路线?

regex - 带空格的 HTML5 表单验证模式字母数字?

regex - 如何在 .htaccess 中使用正则表达式转义 "?"for mod_rewrite

javascript - 如何在 BIRT 上从类路径自动加载 JS 文件

javascript - 在页面加载/刷新时加载随机页面的脚本?

javascript - 我可以编写一个正则表达式,其中一个符号匹配两次吗?

regex - 如何从 Perl 字符串中提取不同数量的数字组?

regex - 将匹配的值传递给函数,并替换为返回值