如何使用 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/