开发者

Javascript - get strings inside a string

var str = '<div part="1">
    <div>
            ...
        <p class="so">text</p>
            ...
    </div>
</div>&l开发者_开发问答t;span></span>';

I got a long string stored in var str, I need to extract the the strings inside div part="1". Can you help me please?


you could create a DOM element and set its innerHTML to your string. Then you can iterate through the childNodes and read the attributes you want ;)

example

var str = "<your><html>";

var node = document.createElement("div");
node.innerHTML = str;

for(var i = 0; i < node.childNodes.length; i++){
   console.log(node.childNodes[i].getAttribute("part"));
}


If you're using a library like JQuery, this is trivially easy without having to go through the horrors of parsing HTML with regex.

Simply load the string into a JQuery object; then you'll be able to query it using selectors. It's as simple as this:

var so = $(str).find('.so');

to get the class='so' elememnt.

If you want to get all the text in part='1', then it would be this:

var part1 = $(str).find('[part=1]').text();

Similar results can be achieved with Prototype library, or others. Without any library, you can still do the same thing using the DOM, but it'll be much harder work.

Just to clarify why it's a bad idea to do this sort of thing in regex:

Yes, it can be done. It is possible to scan a block of HTML code with regex and find things within the string.

However, the issue is that HTML is too variable -- it is defined as a non-regular language (bear in mind that the 'reg' in 'regex' is for 'regular').

If you know that your HTML structure is always going to look the same, it's relatively easy. However if it's ever going to be possible that the incoming HTML might contain elements or attributes other than the exact ones you're expecting, suddenly writing the regex becomes extremely difficult, because regex is designed for searching in predictable strings. When you factor in the possibility of being given invalid HTML code to parse, the difficulty factor increases even more.

With a lot of effort and good understanding of the more esoteric parts of regex, it can be done, with a reasonable degree of reliability. But it's never going to be perfect -- there's always going to be the possibility of your regex not working if it's fed with something it doesn't expect.

By contrast, parsing it with the DOM is much much simpler -- as demonstrated, with the right libraries, it can be a single line of code (and very easy to read, unlike the horrific regex you'd need to write). It'll also be much more efficient to run, and gives you the ability to do other search operations on the same chunk of HTML, without having to re-parse it all again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜