0

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

4 Answers 4

2

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());
}); 
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.