Regexp to pull input tags out of form
This question already has an answer here:
Regexes are fundamentally bad at parsing HTML (see Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why). What you need is an HTML parser. See Can you provide an example of parsing HTML with your favorite parser? for examples using a variety of parsers.
Why can't you just 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);
Note, the above regular expression is not reliable and will not work in ALL situations, hence why you should use the DOM! :)
You can use document.createElement
to create some element and then (ab)use it's innerHTML
property to create a DOM from a 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 might have to manually remove your <html>
tags beforehand though as IE has trouble parsing full documents (if I remember correctly).
上一篇: JAVA正则表达式去除html标签和内容
下一篇: 正则表达式将输入标签拉出窗体