Regexp pulls input tags from a form

I am trying to extract tags <input >

from a tag <form>

. I created a regexp that can identify all tag <form>

and all code to the end </form>

, but I can't figure out how to match everything <input[^>]+>

inside that.

EDIT: The data is a string. I cannot use DOM functions because it is not part of the document. if I paste it in a hidden tag it changes the page layout because the string contains the entire HTML page including links to external stylesheets.

0


a source to share


3 answers


Regexes are fundamentally bad at parsing HTML (see Can you give some examples of why it is difficult to parse XML and HTML with regex? For what). You need an HTML parser. See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.



+3


a source


Why can't you use the DOM?

var inputFields = document.getElementById('form_id').getElementsByTagName('input');
for (var i = 0, l = inputFields.length; i < l; i++) {
    // Do something with inputFields[i] ...
}

      

If you must use regex:



var formHTML = document.getElementById('form_id').innerHTML;
var inputs = formHTML.match(/<input.+?\/?>/g);

      

Please note that the above regex is not reliable and will not work in all situations, so you must use the DOM! :)

+2


a source


You can use document.createElement

to create some element and then (ab) use it innerHTML

to create DOM from string:

var html = document.createElement("div");
html.innerHTML = "<form><input/><input/><input/></form>";

// now you can use dom methods, e.g. getElementsByTagName
var inputs = html.getElementsByTagName("input");
var foo = inputs[0].value; // ...

      

You may have to manually remove the tags <html>

ahead of time as since IE is having a problem parsing full documents (if I remember correctly).

0


a source







All Articles