简体   繁体   English

将变量添加到regexp匹配javascript

[英]Add variable to regexp match javascript

How to add a variable to regexp match javascript? 如何在regexp匹配javascript中添加变量?

var element = "table",
    attr = "id",
    elementId = "listtable";

var res = '<table id="listtable"><tr>test</tr></table>'.match(new RegExp('<table(.+?)>(.+?)\</table>', 'gi'));
console.log(res);

result: ["<table id="listtable"><tr>test</tr></table>"] 结果: ["<table id="listtable"><tr>test</tr></table>"]

How to get a result like this: ["<table id="listtable"><tr>test</tr></table>", "<tr>test</tr>"] 如何获得这样的结果: ["<table id="listtable"><tr>test</tr></table>", "<tr>test</tr>"]

Thanks in advance. 提前致谢。

You can do that by removing the global flag. 您可以通过删除全局标志来做到这一点。 If you specify a global flag in your regular expression, the returned array will contain just an array of matches. 如果在正则表达式中指定全局标志,则返回的数组将仅包含匹配项数组。 If you don't use the global flag, it will return an array of the whole match, and each of its capturing groups. 如果不使用全局标志,它将返回整个匹配项及其每个捕获组的数组。

In your case, you'll need the following: 对于您的情况,您将需要以下内容:

var res = '<table id="listtable"><tr>test</tr></table>'.match(new RegExp('<table(.+?)>(.+?)\</table>', 'i'));
console.log(res); //["<table id="listtable"><tr>test</tr></table>", " id="listtable"", "<tr>test</tr>"]

so that's simply without the g in the flags. 所以这只是在标记中没有g

How about you use the native HTML parser, rather than regex? 您如何使用本机HTML解析器而不是正则表达式? You can do something like: 您可以执行以下操作:

var str = '<table id="listtable"><tr>test</tr></table>';
var div = document.createElement("div");
div.innerHTML = str;

// A tbody is automatically created in a table
// You could also do tr.outerHTML if you know there will be a tr
var content = div.querySelector("tbody").innerHTML; // <-- "<tr>test</tr>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM