Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added string.stripTags() #14

Merged
merged 3 commits into from
Feb 13, 2014
Merged
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
19 changes: 19 additions & 0 deletions lib/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 : '';
});
}

})();

Expand Down
10 changes: 10 additions & 0 deletions test/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down