-5
var str = '<h2 id="test1">11</h2><h2 id="test2">22</h2>'
var arr1 = ["test1","test2"]
var arr2 = ["11","22"]

How can i get arr1/arr2 from str?

Sunshy
  • 1
  • 1

3 Answers3

1

In real life, elements of your interest may be interleaved with other elements, having also e.g. id attributes. So the regex to get the text after id=" up to the next " may be not enough.

The situation is even worse, when you want to retrieve the text content of the element, especially if it contains its own child elements.

So in the case of HTML it is generally much easier and more natural to use DOM methods and attributes, instead of regex.

You can e.g. create a DOM element and set its inner HTML (from your string).

Then, you can retrieve its child elements, e.g. by tag name and process them in a loop.

Then (in the loop), having each current element, you can get either any its attribute or inner text and push it into a respective array (created before).

So the example Javascript fragment, demonstrating the methods to use, can look like below:

<script>
var str = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
var el = document.createElement('div');
el.innerHTML = str;
var elems = el.getElementsByTagName('h2');
var arr1 = [], arr2 = [];
for (var i = 0; i < elems.length; i++) {
  var currElem = elems[i];
  arr1.push(currElem.getAttribute("id"));
  arr2.push(currElem.innerText);
}
document.write('arr1: ' + arr1);
document.write('<br/>');
document.write('arr2: ' + arr2);
</script>

Of course, your final goal is not to write the arrays to the document, but make of them any use you intend, so I wrote document.write only for demonstration purpose.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

get your ids using the following regex

var str = '<h2 id="123"></h2><h2 id="123"></h2>'; 
var res = str.match(/(id="(.*?)(\"))/g);
Murtaza Hussain
  • 3,851
  • 24
  • 30
0

You can use this code, it will return exact what you want.

<script type="text/javascript">

    var str1 = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
    var str2 = '<h2 id="test1">11</h2><h2 id="test2">22</h2>';
    var pattern_id = /id=\"([a-zA-Z0-9-]+)\"/;
    var pattern_value = /\>(\d+)\</;
    var id_array = [];
    var value_array = [];

    do {
         var array = str1.match(pattern_id);
         if(array != null)
         {
            id_array.push(array[1]);
            str1 = str1.replace(pattern_id, '');
         }
    }while(array != null);

    do {
         var array = str2.match(pattern_value);
         if(array != null)
         {
            value_array.push(array[1]);
            str2 = str2.replace(pattern_value, '');
         }
    }while(array != null);

    console.log(id_array); // id are stored here ex: test1, test2
    console.log(value_array); // value are stored here, 11, 22

</script>
Subhendu Mondal
  • 121
  • 1
  • 9