开发者

javascript regex multiple occurrence

i have javascript variable having value

var ull="<ul><li>sunil here from mandya </li><开发者_运维技巧;li>kumar here</li></ul>"

i want output of alert message of each list content like below 1st alert message =sunil here from mandya 2nd alert message =kumar here

how to accomplish this with regex,please help,, i am new to this


It's not recommended to use a regex on HTML. An XML parser would be better. And even better than that would be using javascript. This will output what you're looking for

var li = document.getElementsByTagName('li');
var liLength = li.length;
for(i=0;i<liLength;i++){
  if(document.all){ //IE
      alert(li[i].innerText);
  }else{ //Firefox
      alert(li[i].textContent);
  }
}

An alternative, which would be better supported than writing these things yourself would be to use a javascript framework, such as jQuery (like richardtallent suggests).

You'd be able to do something with that in a much less verbose manner, like:

$('li').each(function(){
   alert($(this).text());
}); 


Don't use regex to parse html, use a parser instead

var p = new DOMParser(); 
var ul = p.parseFromString("<ul><li>sunil here from mandya </li>" +
           "<li>kumar here</li></ul>", "text/xml");
var lis = ul.getElementsByTagName("li");
var len = lis.length;
for(var i = 0; i < len; i++)
   alert(lis[i].firstChild.nodeValue);


A better bet would be to use JQuery (or just DOM calls) rather than trying to parse HTML using regex.

Also, you should consider not sending users a series of alert() modal dialogs, that would be very annoying to many users.


var str = '<ul><li>sunil here from mandya </li><li>kumar here</li></ul>';
var haystack = str;

var match = haystack.match(/<li>(.+?)<\/li>/);
while (match) {
  alert(match[1]);
  haystack = haystack.slice(match[0].length);
  match = haystack.match(/<li>(.+?)<\/li>/);
}

Of course, if the HTML is actually on the page, it would be much, much better to iterate through the DOM.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜