NodeJS を使用して、バックエンドで文字列からタグを削除する方法を探しています。ここでのいくつかの回答は試してみることを提案していますnode-validator
が、ドキュメントも回答も具体的な使用方法を説明していません。
たとえば、次のような変数に文字列があります。
入力:
var text = '<p><b>Hello there!</b> I am a string <span class="small">but not a very exciting one!</span></p>'
望ましい出力:
var newText = Hello there! I am a string but not a very exciting one!
ドキュメントにはいくつかのnode-validator
オプションがありますが、最も適切なのは機能だと思いますtrim()
:
var check = require('validator').check,
sanitize = require('validator').sanitize
//Validate
check('test@email.com').len(6, 64).isEmail(); //Methods are chainable
check('abc').isInt(); //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt(); //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);
//Sanitize / Filter
var int = sanitize('0123').toInt(); //123
var bool = sanitize('true').toBoolean(); //true
var str = sanitize(' \t\r hello \n').trim(); //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a'); //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode(); //'<a>'
これを使用して、文字列からタグ (およびクラス) を削除することは可能ですか?
EDIT:私もcheerio
(本質的にjquery)をロードし、次のようなものを使用しようとしていました:
HTML
<div class="select">
<p><b>Hello there!</b> I am a string <span class="small">but not a very exciting one!</span></p>
</div>
JAVASCRIPT
(function() {
var text = $(.select *).each(function() {
var content = $(this).contents();
$(this).replaceWith(content);
}
);
return text;
}
());
しかし、これは'Object '<p><b>Hello....' has no method "contents"'
エラーになります。jQuery の方が簡単な場合は、同様の関数を使用することにオープンです。