Permalink
Browse files

Merge pull request #14 from der-On/patch-1

added string.stripTags()
  • Loading branch information...
2 parents edae82a + 8614d5b commit 77fcd5e85b7dd73a429a6bd7fd5dd264a8443f17 @mde committed Feb 13, 2014
Showing with 29 additions and 0 deletions.
  1. +19 −0 lib/string.js
  2. +10 −0 test/string.js
View
@@ -784,6 +784,25 @@ string = new (function () {
return uuid.join('');
};
+
+ /**
+ @name string#stripTags
+ @public
+ @function
+ @return {String} A String with HTML tags removed.
+ @description Strips HTML tags from a string.
+ @param {String} The string to strip HTML tags from
+ @param {String|Array} A String or Array containing allowed tags. e.g. "<br><p>"
+ */
+ this.stripTags = function(string, allowed) {
+ // taken from http://phpjs.org/functions/strip_tags/
+ var allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
+ var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
+ comments = /<!--[\s\S]*?-->/gi;
+ return string.replace(comments, '').replace(tags, function ($0, $1) {
+ return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
+ });
+ }
})();
View
@@ -404,6 +404,16 @@ tests = {
assert.equal(expected, data);
}
+, 'test stripTags': function () {
+ var html = '<div>foo</div><p>bar<br/>wooby</p>'
+ , expected = 'foobarwooby';
+ assert.equal(string.stripTags(html), expected);
+ }
+, 'test stripTags with allowed <br>': function () {
+ var html = '<div>foo</div><p>bar<br/>wooby</p>'
+ , expected = 'foobar<br/>wooby';
+ assert.equal(string.stripTags(html, '<br>'), expected);
+ }
};
module.exports = tests;

0 comments on commit 77fcd5e

Please sign in to comment.