正则表达式 : How can I surround all words starting with @ with <b> tags?

标签 javascript regex

我想用 <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/

相关文章:

javascript - 如何从渲染器进程调用 Electron API 方法?

javascript - 无法在 Chrome 中为 "cloudfront.net"设置 cookie?

java - 如何在 Java 中将正则表达式与 String.matches 一起使用

r - 使用 R 从文本中提取重叠的类似年份的部分

PHP 正则表达式字母数字受非字母数字限制

javascript - 向 verold 模型对象添加动画

javascript - 为什么不能在 JS 中本地更改历史状态?

java - JUnit 中时区的正则表达式匹配

javascript - 使用 Watir 关闭 "Confirm Navigation"弹出窗口

python - 我在 python 中的正则表达式没有正确递归