开发者

Javascript Conditional Regex with Processing

开发者 https://www.devze.com 2023-01-13 10:45 出处:网络
While converting an old code, I encountered the following problem. Given an HTML string, <Font face=\"Arial\" size=\"21\" color=\"#000000\">

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 s开发者_Python百科ubtract 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??


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号