diff --git a/lib/string.js b/lib/string.js index f574ead..bca8476 100644 --- a/lib/string.js +++ b/lib/string.js @@ -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. "

" + */ + 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 () + var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, + comments = //gi; + return string.replace(comments, '').replace(tags, function ($0, $1) { + return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; + }); + } })(); diff --git a/test/string.js b/test/string.js index a03027c..99f43f6 100644 --- a/test/string.js +++ b/test/string.js @@ -404,6 +404,16 @@ tests = { assert.equal(expected, data); } +, 'test stripTags': function () { + var html = '

foo

bar
wooby

' + , expected = 'foobarwooby'; + assert.equal(string.stripTags(html), expected); + } +, 'test stripTags with allowed
': function () { + var html = '
foo

bar
wooby

' + , expected = 'foobar
wooby'; + assert.equal(string.stripTags(html, '
'), expected); + } }; module.exports = tests;