我想用大字头开头的所有单词包围@ <b>带有javascript正则表达式的标签.我会用什么模式?
var sample = "@sample";
sample = sample.replace(/(^|\s|-)+@(\w+)/g, "<b>$&</b>");
//^^that's assuming you want the @ to stay
//if not, use $2 instead of $&
Run Code Online (Sandbox Code Playgroud)
$& 插入匹配的子字符串.
使用功能:
var sample = "@sample";
sample = sample.replace(/(^|\s|-)+@(\w+)/g, function(str) {
return "<b>"+str+"</b>";
}
Run Code Online (Sandbox Code Playgroud)
当你想要更强或更好的控制时,使用函数是个好主意.您可能想要处理当前匹配的部分.任何你想要的.