场景
有个需求,后台文章编辑的是富文本,app显示有问题,但是app处理话标签比较麻烦,web端是可以的,因此,方案1是让app请求一个web页面,web页面获取我们的富文本原始内容,然后通过正则转换,方案2是在后台调用前端已经调试好的正则,直接给app,效果更好。
但是js的正则比较灵活,java的正则写法太过麻烦,不想折腾了,于是,我想到了可以调用java内置的js引擎,直接使用前端给的js正则即可。
具体操作如下:
1.准备js正则,放在springboot工程resource文件夹下:
formatH5内容如下:
'use strict'; function getFormatRichText(html) { var newContent = undefined; newContent = html.replace(/<img[^>]*>/gi, function (match) { var resolve = undefined; resolve = match.replace(/style="[^"]+"/gi, function (styleMatch) { var arr = styleMatch.split('='); arr[1] = arr[1].substr(0, arr[1].length - 1) + 'width:100%;"'; return arr.join('='); }); resolve = match.replace(/width="[^"]+"/gi, ''); resolve = match.replace(/height="[^"]+"/gi, ''); return resolve; }); newContent = newContent.replace(/style="[^"]+"/gi, function (match) { var resolve = match.replace(/width:[^;]+;/gi, 'max-width:100%;'); resolve = resolve.replace(/min-max-width:[^;]+;/gi, 'min-width:100%;'); resolve = resolve.replace(/max-max-width:[^;]+;/gi, 'max-width:100%;'); return resolve; }); newContent = newContent.replace(/<br[^>]*\/>/gi, ''); return newContent; }
2.业务代码
public BusinesArticle appInfo(String articleId) { //获取文章内容 BusinesArticle article = getById(articleId); if(StringUtils.isNotBlank(article.getArticleContent())){ try{ ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); //获取文件路径 // File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+ "formatH5.js"); InputStream inputStream = RegionUtil.class.getResourceAsStream("/formatH5.js"); InputStreamReader reader = new InputStreamReader(inputStream); //执行文件 engine.eval(reader); Invocable invocable = (Invocable) engine; //调用js中函数 String result = (String) invocable.invokeFunction("getFormatRichText", article.getArticleContent()); logger.info(result); article.setArticleContent(result); }catch (Exception e){ e.printStackTrace(); } } return article; }
3.注意问题
1.java8-java15只能解析es5
2.读取文件必须用流方式
完