3

我正在寻找一种使用 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('&lt;a&gt;').entityDecode();      //'<a>'

是否可以使用它从字符串中剥离标签(以及类)?

编辑:我也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 更容易,我愿意使用类似的功能。

4

3 回答 3

9

我不使用节点验证器,但这样的东西对我有用

var text = '<p><b>Hello there!</b> I am a string <span class="small">but not a very    exciting one!</span></p>

text.replace(/(<([^>]+)>)/ig,"");

输出

你好呀!我是一个字符串,但不是一个非常令人兴奋的!

现在您可以使用节点验证器对其进行修剪。

从这里得到代码片段

于 2013-06-05T11:54:33.683 回答
7

您可以使用 string.js节点模块获得所需的输出。您可以使用节点安装它

这是我使用的代码-->

var S = require('string');
var text = '<p><b>Hello there!</b> I am a string <span class="small">but not a very exciting one!</span></p>';
console.log(text);
text = S(text).stripTags().s;
console.log(text);

输出-

<p><b>Hello there!</b> I am a string <span class="small">but not a very exciting one!</span></p>
Hello there! I am a string but not a very exciting one!

如何安装 string.js ?

npm install --save string

进一步参考

于 2014-12-29T09:32:09.723 回答
2

看起来 node-validator 没有内置任何类型的 HTML 标记剥离,trim()因为它似乎只能指定要删除的单个字符,所以不起作用。它非常容易扩展,因此您可以为其编写扩展以去除 HTML 标记。

否则,您可以使用cheerio .text()( docs ) 方法来获取元素及其后代的组合文本内容。

像这样的东西应该工作:

$('.select *').each(function() {
    var content = $(this).text();
    $(this).replaceWith(content);
}

这将删除 a 中的任何 html ,如果您也想替换,请.select删除。*.select

于 2013-06-05T10:30:46.657 回答