简体   繁体   中英

Add variable to regexp match javascript

How to add a variable to regexp match 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>"]

How to get a result like this: ["<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.

How about you use the native HTML parser, rather than regex? 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>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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