Convert "pt" to "px" using regex

In the 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 it possible to change the associated pt value to px using a regular expression.

162pt can be 162 * 96 / 72px.

We are looking for your help.

+6
javascript regex
source share
2 answers

You can use a regular expression for this, in which you pass the function to String#replace :

 s = /* ...the data... */; s = s.replace(/([0-9]+)pt/g, function(match, group0) { return Math.round(parseInt(group0, 10) * 96 / 72) + "px"; }); 

Living example

When you provide a function for the second argument to replace, it is called for each match, with a complete match as the first argument, and then the value of any capture groups for subsequent arguments; as a replacement, the return value is used. So above, I use the capture group to capture the number, and then do the math and return a new line.

You may need or want to tweak the regex a bit to make sure it matches your data (possible spaces between numbers and ones, maybe the i flag to match "PT" as well as "pt", etc.) but what a fundamental approach.

+17
source share

In addition to the TJ Solution: Since pt values ​​are often non-integer (e.g. 237.36pt), it would be very useful to change regexp to match numbers without and optionally with a decimal point, otherwise this part of the regular expression matches only the partial part (i.e. 36pt in our example), and the callback will produce the wrong value. This regex should fix this problem:

 /([0-9]*\.?[0-9]+)pt/g 
0
source share

All Articles