我想用 <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 $&
$&
插入匹配的子字符串。
使用函数:
var sample = "@sample";
sample = sample.replace(/(^|\s|-)+@(\w+)/g, function(str) {
return "<b>"+str+"</b>";
}
当您想要更好地控制时,使用函数是个好主意。您可能想要处理当前匹配的片段。随心所欲。
查看更多here at MDC .
关于正则表达式 : How can I surround all words starting with @ with <b> tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1180872/