admin管理员组文章数量:1237493
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.
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.
Share Improve this question asked Dec 21, 2010 at 6:52 NazmulNazmul 7,21812 gold badges53 silver badges64 bronze badges 3- 2 I don't think you can do math with regex. – BoltClock Commented Dec 21, 2010 at 6:55
-
1
@BoltClock: No, but you can with
String#replace
and a callback. :-) – T.J. Crowder Commented Dec 21, 2010 at 6:59 - 96/72 came from stackoverflow./questions/139655/… – Nazmul Commented Dec 21, 2010 at 7:10
2 Answers
Reset to default 20You 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 plete 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
本文标签: javascriptConvert quotptquot to quotpxquot using regular expressionStack Overflow
版权声明:本文标题:javascript - Convert "pt" to "px" using regular expression - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739898156a2206619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论