javascript - 如何在不创建格式错误的 HTML 标签的情况下分解字符串?

标签 javascript html node.js parsing html-parsing

我在做什么:

  • 在 NodeJS 中,我使用 MustacheJS 使用 JSON 对象数组中的数据创建电子邮件模板。
  • 模板中的文本/消息可以包含文本和基本 html 标记(例如 b pa )。
  • 由于空间有限,我只需显示消息的摘录。为此,我进行了字数统计,在说 20 个单词(通过空格检查)后,我 chop 字符串并附加 View more anchor 标记。这会将其链接到网站的帖子页面,其中包含完整的帖子。比如:

Hey this is a sample post text <b>message</b>. Lorem ipsum dolor sit amit... <a href="someurl">View more</a>

问题:

在字数统计和 chop 期间,我可能会 chop html 标记之间的字符串,因为我只是根据空间计算字数。像这样的东西:

I am sharing a link with you. <a style="color:... <a href="someurl">View more</a>

现在这会破坏 html。

可能的解决方案:

  • 在 chop 字符串之前,对其运行正则表达式以查找其中的所有 html 标签。
  • 使用indexOf() (或其他方法)查找每个标签的开始和结束索引。
  • 字数统计后,获取需要 chop 的索引。
  • 现在查看索引是否与任何标记区域相交。
  • 如果确实相交,只需将 chop 索引移动到 html 标记的开头或结尾即可。

问题:

有没有更好的方法来做到这一点。我不知道应该在 Google 上搜索哪些搜索词才能获得相关帮助。

附注该代码很灵活,如果有明显更好的解决方案,我可以更改流程。另外,我不擅长帖子标题。如果可以的话,请将其修改为反射(reflect)问题的内容。

<小时/>

编辑:

这是我在 Alex 回答后想到的。希望它对其他人有帮助:

/**
 * Counter: Takes a string and returns words and characters count
 * @param value
 * @returns obj: {
 *      'wordCount': (int),
 *      'totalChars': (int),
 *      'charCount': (int),
 *      'charCountNoSpace': (int)
 *  }
 */
var counter = function(value){
    var regex = /\s+/gi;
    if (!value.length) {
        return {
            wordCount: 0,
            totalChars: 0,
            charCount: 0,
            charCountNoSpace: 0
        };
    }
    else {
        return {
            wordCount: value.trim().replace(regex, ' ').split(' ').length,
            totalChars: value.length,
            charCount: value.trim().length,
            charCountNoSpace: value.replace(regex, '').length
        };
    }
}


/**
 * htmlSubString - Creates excerpt from markup(or even plain text) without creating malformed HTML tags
 * @param markup {string} - Markup/text to take excerpt out of
 * @param limit {int} - Total word count of excerpt. Note that only text (not the html tag) counts as a valid word.
 * @returns {string} - Excerpt
 */
var htmlSubString = function(markup, limit){
    var htmlParser = require("htmlparser2");
    var tagCount = 0;
    var wordCount = 0;
    var excerpt = '';

    function addToExcerpt(type, text, attribs) {
        if ((wordCount >= limit && tagCount == 0) || (tagCount === 1 && type === 'tagOpen' && wordCount >= limit)) {
            return false;
        }
        else if (wordCount < limit || tagCount) {
            if (type === 'text') {
                var wordCountSubString = $scope.counter(text).wordCount;
                if (wordCountSubString + wordCount > limit && tagCount === 0) {
                    var length = limit - wordCount;
                    var wordList = text.trim().split(' ');

                    for (var i = 0; i < length; i++) {
                        excerpt += ' ' + wordList[i];
                        wordCount++;
                    }
                } else {
                    wordCount += wordCountSubString;
                    excerpt += text;
                }

            } else if (type === 'tagOpen') {
                excerpt += '<' + text;
                for (var prop in attribs) {
                    excerpt += ' ' + prop + '="' + attribs[prop] + '"';
                }
                excerpt += '>';
            } else if (type === 'tagClose') {
                excerpt += '</' + text + '>';
            }
        }

        return true;
    }

    var parser = new htmlParser.Parser({
        onopentag: function (name, attribs) {
            if(wordCount < limit){
                ++tagCount;
                addToExcerpt('tagOpen', name, attribs);
            }
        },
        ontext: function (text) {
            if(wordCount < limit){
                addToExcerpt('text', text);
            }
        },
        onclosetag: function (tagName) {
            if(wordCount < limit || tagCount > 0){
                addToExcerpt('tagClose', tagName);
                --tagCount;
            }
        }
    });

    parser.write(markup);
    parser.end();

    return excerpt;
}

用法:

var wordCountLimit = 20;
var markup = "/* some markup/text */";
var excerpt = htmlSubString(markup, wordCountLimit);

最佳答案

现在,您一定能够找到一些与正则表达式匹配的 HTML 标记。也就是说,我不推荐它。一开始你会很高兴,一切都会顺利。然后明天你就会发现一个小边缘情况。 “不用担心!”当您修改表达式以解决差异时,您会说。然后第二天,一个新的调整,一个新的调整,又一个,等等,直到你再也无法忍受为止。

我强烈建议您找到一个已经建立的 HTML 解析库。 npm 上好像有不少。 This one看来相当受欢迎。

PS - 你的问题回答得很好。我希望更多的问题能花同样多的时间并提供尽可能多的细节:)

关于javascript - 如何在不创建格式错误的 HTML 标签的情况下分解字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423229/

相关文章:

javascript - Node.js:Facebook 返回给我未定义而不是个人资料?

javascript - 使用 For 循环时不显示 .innerHTML

html - 如何使用 CSS 和 HTML5 创建没有图像的斜 Angular 按钮

javascript - 连接 4 在 html Canvas 上不显示

javascript - 根据按下的按钮更改表单方法

javascript - 旋转木马外的导航控件 - Zurb Foundation Orbit

javascript - Mongoose - 在对象中填充对象

node.js - 如何将 Node.js 应用程序上传到 FTP 服务器?

javascript - 如何使用 Ruby 验证 webhook? (在 rails 中)

javascript - 如何使用选项卡从 Ext.FormPanel 提交数据?