Je sais que c'est une réponse tardive, mais si vous pouvez toujours utiliser sanitize-html Il est écrit pour le nœud, mais assez sûr que vous pourriez courir browserify à la bibliothèque (ou votre code d'ailleurs). Notez qu'il utilise lodash, donc si vous l'utilisez déjà, vous voudrez peut-être ajuster le paquet.
Cet exemple est plus que ce que vous cherchez ... J'utilise cette bibliothèque afin de nettoyer le code d'entrée, en convertissant à la démarque pour le stockage dans la DB à partir d'ici, je réhydrate via marked.
// convert/html-to-filtered-markdown.js
'use strict';
var sanitize = require('sanitize-html') //https://www.npmjs.org/package/sanitize-html
,toMarkdown = require('to-markdown').toMarkdown
;
module.exports = function convertHtmlToFilteredMarkdown(input, options) {
if (!input) return '';
options = options || {};
//basic cleanup, normalize line endings, normalize/reduce whitespace and extra line endings
var response = (input || '').toString().trim()
.replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings
.replace(/“/g, '"') //remove fancy quotes
.replace(/”/g, '"') //remove fancy quotes
.replace(/‘/g, '\'') //remove fancy quotes
.replace(/’/g, '\'') //remove fancy quotes
;
//sanitize html input
response = sanitize(response, {
//don't allow table elements
allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ],
//make orderd lists
transformTags: {
'ol': 'ul'
}
}).replace(/\r\n|\r|\n/g,'\n') //normalize line endings;
if (!options.tables) {
response = response.replace(/[\s\n]*\<(\/?)(table|thead|tbody|tr|th|td)\>[\s\n]*/g, '\n\n') //replace divs/tables blocks as paragraphs
}
//cleanup input further
response = response
.replace(/[\s\n]*\<(\/?)(div|p)\>[\s\n]*/g, '\n\n') //divs and p's to simple multi-line expressions
.replace(/\>#/g, '\n\n#') //cleanup #'s' after closing tag, ex: <a>...</a>\n\n# will be reduced via sanitizer
.replace(/\\s+\</,'<') //remove space before a tag open
.replace(/\>\s+\n?/,'>\n') //remove space after a tag close
.replace(/\&?nbsp\;?/g,' ') //revert nbsp to space
.replace(/\<\h[12]/g,'<h3').replace(/\<\/\h[12]/g,'</h3') //reduce h1/h2 to h3
;
//convert response to markdown
response = toMarkdown(response);
//normalize line endings
response = response
.replace(/(?:^|\n)##?[\b\s]/g,'\n### ') //reduce h1 and h2 to h3
.replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings
.trim()
return response + '\n';
}
Tout d'abord, merci! Ça marche. Ma seule question est de savoir s'il est possible ou non de tout faire en un seul remplacement(). Les fichiers HTML peuvent potentiellement être très volumineux et l'efficacité est la clé. Je vais jouer avec ça. – thechriskelley
@thechriskelley: ajouté une solution dans un "remplacer" – thejh
Excellent, merci! – thechriskelley