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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>"

1 Comment

You could also use DOMParser instead of creating a div. See developer.mozilla.org/en-US/docs/Web/API/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.