From bfe947ddc9e3a8333e19b580fc0330075ed63022 Mon Sep 17 00:00:00 2001 From: k Date: Sun, 28 Jul 2013 11:11:46 +0300 Subject: [PATCH 1/2] Addigh a allowed tags param. --- index.js | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) 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(); + } } From 8040e823ac53b69c72cf236abf983805797cc65c Mon Sep 17 00:00:00 2001 From: MykolaPrymak Date: Mon, 29 Jul 2013 10:27:52 +0300 Subject: [PATCH 2/2] Update README.md Add more examples. --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) 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." ``` ![](https://dl.dropbox.com/s/9q2p5mrqnajys22/npmel.jpg?token_hash=AAHqttN9DiGl63ma8KRw-G0cdalaiMzrvrOPGnOfDslDjw)