【问题标题】:Variables in regex [duplicate]正则表达式中的变量[重复]
【发布时间】:2017-11-04 13:05:18
【问题描述】:

我正在尝试在 JavaScript 中的正则表达式中使用变量。

考虑这个函数,它将提取给定字符串中<b></b> 标记之间的所有文本

function Tags_Content_B(html)
{
 return html.match(/<b>(.*?)<\/b>/g).map(function(val){return val.replace(/<\/?b>/g,'');});
}

为了使函数更通用,我想添加第二个参数:我想从中提取内容的标签。按照其他有关如何在正则表达式中使用变量的示例,我尝试了这个

function Tags_Content(html, tag)
{
 var match_exp   = new RegExp("/<" + tag + ">(.*?)<\/" + tag + ">/g");
 var replace_exp = new RegExp("/<\/?" + tag +">/g");

 return html.match(match_exp).map(function(val){return val.replace(replace_exp,'');});
}

但是它不起作用,没有匹配,没有替换。 关于我做错了什么的任何提示?

【问题讨论】:

  • 请不要使用正则表达式来解析 HTML...使用具有实际安全措施的行业标准解析器来防止 XSS 攻击。
  • 这只是一个个人的“业余爱好”项目,对外和/或专业用途零接触
  • 你读过the documentation about RegExp吗?查看示例。
  • 你校对你的帖子了吗? &lt;b&gt; 等标签必须用反引号分隔,否则它们将消失。
  • 如文档所述,使用RegExp 构造函数时,不要包含/ 的开头和结尾字符,并指定标志(g)作为第二个参数。 replace 的参数也不能是正则表达式本身——这意味着什么?

标签: javascript html regex


【解决方案1】:

理解你永远不应该实际上这样做:

function Tags_Content(html, tag) {
  var match_exp = new RegExp("<" + tag + ">(.*?)</" + tag + ">", "g");
  var replace_exp = new RegExp("</?" + tag + ">", "g");

  return html.match(match_exp).map(function(value) {
    return value.replace(replace_exp, '');
  });
}

console.log(Tags_Content("Let's <b>test</b> the <code>b</code> tag <b>people!</b>", "b"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2011-08-19
    • 1970-01-01
    • 2015-01-21
    • 2013-06-17
    相关资源
    最近更新 更多