0

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.

owl
  • 4,201
  • 3
  • 22
  • 28

2 Answers2

2

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.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
2

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>"
soktinpk
  • 3,778
  • 2
  • 22
  • 33
  • You could also use DOMParser instead of creating a div. See https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Parsing_an_SVG_or_HTML_document – Joeytje50 May 27 '14 at 19:11