Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ $ npm install strip
```js
strip('<p> hello <a href="http://foo.com/?q=123">world</a> </p>');
// => Hello World

strip('<p>My name is <b>Jon</b>.</p>');
// => Retrun "My name is Jon."

strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>');
// => Retrun "My name is Jon. I love dogs."

strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>', 'a');
// => "My name is Jon. I love <a href="en.wikipedia/wiki/dogs">dogs</a>."

strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>', 'a|b');
// => "My name is <b>Jon</b>. I love <a href="en.wikipedia/wiki/dogs">dogs</a>."
```

![](https://dl.dropbox.com/s/9q2p5mrqnajys22/npmel.jpg?token_hash=AAHqttN9DiGl63ma8KRw-G0cdalaiMzrvrOPGnOfDslDjw)
31 changes: 29 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -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('<p>My name is <b>Jon</b>.</p>'); // Retrun "My name is Jon."
* var text = strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>'); // Retrun "My name is Jon. I love dogs."
* var text = strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>', 'a'); // Retrun "My name is Jon. I love <a href="en.wikipedia/wiki/dogs">dogs</a>."
* var text = strip('<p>My name is <b>Jon</b>.</p><p>I love <a href="en.wikipedia/wiki/dogs">dogs</a>.</p>', 'a|b'); // Retrun "My name is <b>Jon</b>. I love <a href="en.wikipedia/wiki/dogs">dogs</a>."
*
*
* @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();
}
}