Hoque Hoque - 5 months ago 13
Javascript Question

Convert "pt" to "px" using regular expression

In WYSIWYG editor, I have

<TABLE style="WIDTH: 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.

Answer

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.

Comments