Convert "pt" to "px" using regular expression
In WYSIWYG editor, I have
<TABLE style="WI开发者_如何学GoDTH: 162pt; BORDER-COLLAPSE: collapse" border=0 cellSpacing=0 cellPadding=0 width=216>
I can convert this to
<TABLE style="WIDTH: 162px; BORDER-COLLAPSE: collapse" border=0 cellSpacing=0 cellPadding=0 width=216>
using
"wysiwygdata".replace(/pt/g ,"px");
Is there any way to change associated value of pt to the value of px using regex.
162pt might be 162*96/72px.
Looking for your help.
You can use a regular expression for this, where you feed a function into String#replace
:
s = /* ...the data... */;
s = s.replace(/([0-9]+)pt/g, function(match, group0) {
return Math.round(parseInt(group0, 10) * 96 / 72) + "px";
});
Live example
When you supply a function for the second argument of replace, it gets called for each match, with the complete match as the first argument, and then the value of any capture groups for subsequent arguments; the return value is used as the replacement. So above I'm using a capture group to capture the number, and then doing the math and returning the new string.
You might need or want to adjust the regex a bit to make sure it fits your data (possible spaces between the number and the units, possibly the i
flag so it matches "PT" as well as "pt", etc.), but that's the fundamental approach.
In addition to T.J. Crowder solution: Since pt values are often non-integer (for example 237.36pt) it would be very useful to change regexp to match numbers without and optionally with decimal point, otherwise this regexp match fraction part only (i.e. 36pt in our example) and callback will produce incorrect value. This regexp should fix that issue:
/([0-9]*\.?[0-9]+)pt/g
精彩评论