我现在有HTML
代码的字符串,想要对字符串进行排版,有没有什么可用的方法?
需要一款js插件,或者方法,能在项目里面转换用的。
比如原字符串是:
<div><p>This is a p</p><p>This is another p</p></div>
添加空格和换行,变成新的字符串:
<div>
<p>This is a p</p>
<p>This is another p</p>
</div>
我现在有HTML
代码的字符串,想要对字符串进行排版,有没有什么可用的方法?
需要一款js插件,或者方法,能在项目里面转换用的。
比如原字符串是:
<div><p>This is a p</p><p>This is another p</p></div>
添加空格和换行,变成新的字符串:
<div>
<p>This is a p</p>
<p>This is another p</p>
</div>
为什么我这个问题一直被踩?还是一个不错的问题的嘛。。。。
@mqycn , @zhenguoli
这是朋友@candy写的一个方案:
import _ from 'lodash';
const splitOnTags = str => str.split(/(<\/?[^>]+>)/g).filter(line=>line.trim()!="");
const isTag = str => /<[^>!]+>/.test(str);
const isClosingTag = str => /<\/[^>]+>/.test(str);
const isSelfClosingTag = str => /<[^>]+\/>/.test(str);
const isOpeningTag = str => isTag(str) && !isClosingTag(str) && !isSelfClosingTag(str);
export default (str, indent) => {
let depth = 0;
indent = indent || ' ';
return splitOnTags(str).map(item=>{
if(isClosingTag(item)) {
depth--;
}
const line = _.repeat(indent, depth) + item;
if(isOpeningTag(item)) {
depth++;
}
return line;
}).join('\n');
}
对开发工具而言,你可以尝试 VSCode 编辑器。
https://code.visualstudio.com/
安装完成后,按 shift-ctrl-x 打开插件列表,搜索 Beautify 并安装,即可实现 HTML 代码美化。
相应设置参考这里:
https://marketplace.visualstu...
在代码中进行格式转换可以使用 HTML String Parser,例如
https://www.npmjs.com/package...
或者使用 cheerio 解析 DOM 文本后重新输出亦可。
3.(重新制作一个 HTML Parser 并不困难,参考我的专栏
http://ewind.us/2016/toy-html...
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
第一种方案想用正则做答没成功,没有成功。
整理了下思路,已经完美解决(自认为完美)。
以下是循环的老答案: