Umesh Patil
Umesh Patil

Reputation: 10705

extract string with Regular expression

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)

Upvotes: 0

Views: 774

Answers (3)

npinti
npinti

Reputation: 52205

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

Upvotes: 1

Toto
Toto

Reputation: 91518

Instead of exec, use the match method:

res = code.match(patt);

output:

["<? if(byExposure) { ?>", "<?= question.totals["control"] ?>"]

Upvotes: 1

xpapad
xpapad

Reputation: 4456

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]

Upvotes: 0

Related Questions