diff --git a/README.md b/README.md index 57f6201..d60e1aa 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,18 @@ $ npm install strip ```js strip('
hello world
'); // => Hello World + +strip('My name is Jon.
'); +// => Retrun "My name is Jon." + +strip('My name is Jon.
I love dogs.
'); +// => Retrun "My name is Jon. I love dogs." + +strip('My name is Jon.
I love dogs.
', 'a'); +// => "My name is Jon. I love dogs." + +strip('My name is Jon.
I love dogs.
', 'a|b'); +// => "My name is Jon. I love dogs." ```  diff --git a/index.js b/index.js index 51156a4..a242123 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,32 @@ module.exports = strip; -function strip(html){ - return html.replace(/<[^<]+>/g, '').trim(); +/** + * Strip tags from html text. + * You can specify the allowed tag in format 'a', 'p|b' or 'b|i|p' + * + * + * @example + * var text = strip('My name is Jon.
'); // Retrun "My name is Jon." + * var text = strip('My name is Jon.
I love dogs.
'); // Retrun "My name is Jon. I love dogs." + * var text = strip('My name is Jon.
I love dogs.
', 'a'); // Retrun "My name is Jon. I love dogs." + * var text = strip('My name is Jon.
I love dogs.
', 'a|b'); // Retrun "My name is Jon. I love dogs." + * + * + * @function + * @param {String} html HTML string to stip tags + * @param {String} [allowed] Allowed HTML tags + * @return {String} + */ + +function strip(html, allowed) { + // Normalize the allowed format. 'a|b|c' -> '|a|b|c|' + allowed = '|' + (allowed || '').toLowerCase() + '|'; + + if (allowed.length === 2) { + return html.replace(/<[^<]+>/g, '').trim(); + } else { + return html.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, function(tag_body, tag_name) { + return (allowed.indexOf('|' + tag_name.toLowerCase() + '|') === -1) ? '' : tag_body; + }).trim(); + } }