0

I've got this php code that works perfectly:

preg_match_all(
    '/<div style="display:block; float:left; height:240px; width:150px;'
    . ' text-align:center; margin:5px; overflow:hidden;">.*?'
    . '<span class="card-text">(.*?)'
    . '<span class="instruction">\((.*?)\)<\/span>/s',
  $html,
  $students,
  PREG_SET_ORDER
);

foreach($students as $student) {
  echo($student[1].",".$student[2]."<br />");
}

How would I do this in javascript? Thanks!

2
  • in javascript do you have a string with the html or are you traversing the DOM properly? If you are doing this with the DOM (what I would suggest), you would use a completely different method where you would use DOM functions like document.getElementById and parent.getElementsByTagName then loop through those results. Commented Mar 18, 2011 at 22:52
  • It's a string, a very long one. about 500K Commented Mar 18, 2011 at 22:55

1 Answer 1

2

Frankly you should not do this using JavaScript. You should not be trying to parse so much HTML using regular expressions either.

Instead you should consider looking at something like Simple HTML Dom parser

As for a JavaScript solution - JS is a DOM parser!

var student1 = document.getElementsByClassName('card-text')[0];
var student2 = document.getElementsByClassName('instruction')[0];
//echo out

A better solution would be to use jQuery, since you'll have fewer problems with DOM manipulation (its selector engine is fantastic!) see rough example here.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm actually using jquery for other parts of the project, thanks for the quick example, I'll take a look at it.

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.