2

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

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 thanks i made of use of your answer too..bit different context.. works nicely :)
1

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.

Comments

1

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.

Comments

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.