Amitd
Amitd

Reputation: 4849

Javascript Conditional Regex with Processing

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??

Upvotes: 2

Views: 529

Answers (3)

Roy Sharon
Roy Sharon

Reputation: 3518

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.

Upvotes: 1

user113716
user113716

Reputation: 322502

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

Upvotes: 2

Dave Everitt
Dave Everitt

Reputation: 17876

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.

Upvotes: 1

Related Questions