views:

63

answers:

3

Hi All,

While converting an old code, I encountered the following problem.

Given an HTML string,

   <Font face="Arial" size="21" color="#000000"> 
     THIS IS SIZE 21    
    </Font>

I want to subtract a factor "X" from the size "21" in the output string by using Regex?

So the new string be

   <Font face="Arial" size="(21-X)" color="#000000"> 
     THIS IS SIZE (21-X)    
    </Font>

Example

Original String

   <Font face="Arial" size="21" color="#000000"> 
     THIS IS SIZE 21    
    </Font>

and factor = 8 (so subtract 8 from size ..so new size = 21- 8 =13 )

Output String

   <Font face="Arial" size="13" color="#000000"> 
     THIS IS SIZE 13   
    </Font>

Can this type of processing be done using Regex. Something similar to match evaluator in C#

Whats the best way to do this sort of conversions??

+1  A: 

Before going further, the font tag these days has been replaced with CSS (and will be deprecated at some point), so I'd use CSS instead. Apart from that, this page on the Javascript RegExp Object should help.

Dave Everitt
+2  A: 

Try this:

function update(elem, num) {
    var size = elem.getAttribute("size");
    if (size) {
        elem.setAttribute("size", (size - num) );
        elem.firstChild.nodeValue =
            elem.firstChild.nodeValue.replace(/(\d+)/, function(str, p1) {
               return p1 - num;
            });
    }
}
var fonts = document.getElementsByTagName('font');

update(fonts[0],8);
patrick dw
+1 thanks i made of use of your answer too..bit different context..works nicely :)
Amitd
+1  A: 

Try something like the following:

var html = '<Font face="Arial" size="21" color="#000000">\n' +
           '  THIS IS SIZE 21 \n' +
           '</Font>';
var factor = 8;
html = html.replace(/(size=")(\d+)(")/g, function(m, c1, c2, c3) { 
    return c1+(c2-factor)+c3; 
});

The function gets called with the first argument being the full match, followed by the captures. Its return value is used to replace the match inside the result.

Roy Sharon
thx u for the regex answer.. :)
Amitd