0

It is the very little part of HTML code, I want to get the all code wrapped by < ? and ? >.

Simply, I just want to extract the string given below. for example,

   var code='<td>Total Response Sets</td><? if(byExposure) { ?><td style="text-align:right;padding-right:10px"><?= question.totals["control"] ?></td>';

  // how to extract the required code with regular expression ?

After using npinti, I used below code, It gives me first expression between <% & %>. But How do I get next few expressions?

var patt=/<\?\s*(.*?)\s*\?>/g;
var result=patt.exec(code);
console.log(result[1]);  // o/p -> if(byExposure) {

(For more info, Code is used for templating in underscore.js)

Umesh Patil
  • 10,475
  • 16
  • 52
  • 80

3 Answers3

1

This regex:

<\?\s*(.*?)\s*\?>

Should match what you need. From the given string it matches the following:

<? if(byExposure) { ?>

<?= question.totals["control"] ?>

You can then extract the content between your markers using groups. Check this previous SO thread to see how it can be done.

This should get the job done:

var code='<td>Total Response Sets</td><? if(byExposure) { ?><td style="text-align:right;padding-right:10px"><?= question.totals["control"] ?></td>';
var patt=/<\?\s*(.*?)\s*\?>/g;
var result=patt.exec(code);

while (result != null) {
    alert(result[1]);
    result = patt.exec(code);    
}
Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • Thanks, I updated question with your answer, It returns first expression, any idea to get next similar expressions? – Umesh Patil Jan 11 '12 at 11:33
1

Instead of exec, use the match method:

res = code.match(patt);

output:

["<? if(byExposure) { ?>", "<?= question.totals["control"] ?>"]
Toto
  • 89,455
  • 62
  • 89
  • 125
0

I'm not sure what you want to extract. Do you need just the first string between <? and ?> then you can use:

(/<\?(.*?)\?>/.exec( code ))[1]

This will return if(byExposure) {. If you want to match between the first <? and the last ?>, then you can use:

(/<\?(.*?)\?>/.exec( code ))[1]
xpapad
  • 4,376
  • 1
  • 24
  • 25
  • Your code gives only first expression between <% and %>. I wanted array of all such expressions. Thanks for your code :) – Umesh Patil Jan 11 '12 at 11:09