Background is a demand, need to use other local edit good rich content of the text box, I had to get to the show directly, after PC ok, no problem, but the mobile terminal is a problem, the mobile end need to convert the content of the rich text box to the right size, equivalent to a style rewritten, two main problems are, 1 is to convert PX to REM or VW. This article is about converting to REM. 2 is that there may be a problem with the size of the picture, so we need to convert the picture to the specified width and height, such as 375px.

Replace the style inside the IMG tag

The idea is to find each img tag and then find each style=”” and replace it

let a = '<img /> <span style="fsdfxv">sdfdsfsdf</span> <img style="xvxcvxcvs"/>cxcxcxc<img style="fdfdfdsfsdf"/>'; let reg = /<img.*? (style=".*?" ) {0, 1} \ / > / g; let b = a.replace(reg, function ($1, $2) { if ($1.indexOf("style=") > -1) { return $1.replace(/style=".*"/g, 'style="aaaaaaa"') } else { return $1.replace(/\/>/g, 'style="aaaaaaa"/>') } })Copy the code

The main problem is the need to pay attention to regular greed mode by default, the let reg = / < img. * (style = “. * “) {0, 1} \ / > / g;; Under normal circumstances we want to match the first step to write regular img tags, is to think so, but this will find that we have to match up all the string a, including span tags, the reason is that we use. * matching between the miscellaneous things we didn’t take into account the regular matching greed mode by default, emphasizes the match more, .* matches everything, so he matches everything else.

  • The solution is to use the non-greedy model,. *?Can be solved.

Replace the px style of the rich text box with rem for mobile layout

let currentSize = 16; <span style=" max-width: 100%; clear: both; 14px">sdfdsfsdf</span> <img style="xvxcvxcvs"/>cxcxcxc<img style="font-size: 20px"/>'; function fn($1, $2) { let x = $2; let y = currentSize; return `:${x/y}rem` } content.replace(/:\s*(\d+)px/g, fn)Copy the code
  • For example, if you want the size to be 375px; Now you have an image that is 800px, how do you fill the entire screen? First use the first method above, set the width of the image to 375px, and then call the second method, convert it to REM, that is, 375/16rem