Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将html元素插入文本字符串以匹配另一个html字符串_Javascript_Jquery_Html_Css_Compare - Fatal编程技术网

Javascript 将html元素插入文本字符串以匹配另一个html字符串

Javascript 将html元素插入文本字符串以匹配另一个html字符串,javascript,jquery,html,css,compare,Javascript,Jquery,Html,Css,Compare,有两个文件pdf和html,将文件作为纯文本字符串(从pdf中提取文本后)和html读取,现在尝试使纯文本具有与html字符串相同的html标记。然后比较它们,找出差异 简单示例的最终编辑当前不起作用 var text1="here is example text"; var text2="<html><body><div>here is another <span>example</span> text</div><

有两个文件pdf和html,将文件作为纯文本字符串(从pdf中提取文本后)和html读取,现在尝试使纯文本具有与html字符串相同的html标记。然后比较它们,找出差异

简单示例的最终编辑当前不起作用

var text1="here is example text";

var text2="<html><body><div>here is another <span>example</span> text</div></body></html>";

var div = document.createElement("div");
div.innerHTML = text2;
var text = div.textContent || div.innerText || "";

var content=  text.split(" ");
var alltags=text2.match(/<.+?>/g);
var pdfwords=text1.split(" ");
var output="";
for(var j=0; j<alltags.length; j++){
   for(i=0; i<pdfwords.length; i++){
      if(pdfwords[i]===content[j]){

         output+=alltags[i]+pdfwords[i];
      }
    }
}

document.write(output);
var text1=“这里是示例文本”;
var text2=“这里是另一个示例文本”;
var div=document.createElement(“div”);
div.innerHTML=text2;
var text=div.textContent | | div.innerText | |“”;
var content=text.split(“”);
var alltags=text2.match(//g);
var pdfwords=text1.split(“”);
var输出=”;
对于(var j=0;j而言,最简单的方法是

var s="Hello everyone on stackoverflow"
var s_split = s.split(' ');
var y = '<html><head></head><body><div>' + s_split[0] + '<span>' + s_split[1] + '</span>' + s_split[2]+' ' + s_split[3] + '</div></body></html>';
var s=“大家好,stackoverflow上的所有人”
var s_分割=s分割(“”);
变量y=''+s_分割[0]+''+s_分割[1]+''+s_分割[2]+''+s_分割[3]+'';

如果必须换行特定的单词或文本,请选中

,然后搜索并替换它,如下所示:

var f = "Hello everyone on stackoverflow";
var o = "Hello";
var e = "everyone on";
var s = "stackoverflow";

if (f.indexOf(e) >= 0) {
    var h = f.replace(e,"<strong>"+e+"</strong>");
}else{
    var h = f;
}
if (h.indexOf(s) >= 0){
    var h = h.replace(s,"<em>"+s+"</em>");
}
if (h.indexOf(o) >= 0){
    var h = h.replace(o,"<u>"+o+"</u>");
}

$('body').append('<div>'+h+'</div>');
var f=“大家好,stackoverflow上的每个人”;
var o=“你好”;
var e=“每个人都在”;
var s=“stackoverflow”;
如果(f.indexOf(e)>=0){
var h=f。替换(e,“”+e+””;
}否则{
var h=f;
}
如果(h.indexOf(s)>=0){
var h=h。替换(s,“+s+”);
}
如果(h.indexOf(o)>=0){
var h=h。替换(o,“+o+”);
}
$('body')。追加(''+h+'');

这里的示例:

为什么不简单地去掉html标记并比较文本呢

var s = "Hello everyone on stackoverflow";

var y = "<html><head><head><body><div>Hello<span>everyone</span>on stackoverflow</div></body></html>";

//using regular expressions match HTML tags and replace them with empty string. Make sure to trim the output so that the extra whitespaces at either end are removed.
var z = y.replace(/(<([^>]+)>)/ig, ' ').trim();

//compare if the stripped string matches the other string.
if(z == s) {
    s = y;  
}
alert(s);
var s=“大家好,stackoverflow上的每个人”;
var y=“Helloeveryoneon stackoverflow”;
//使用正则表达式匹配HTML标记并将其替换为空字符串。请确保修剪输出,以便删除两端多余的空格。
var z=y.replace(/(]+)>)/ig',).trim();
//比较剥离字符串是否与其他字符串匹配。
如果(z==s){
s=y;
}
警报;

这是一个简单的解决方案,可以满足您的需求,是一个动态解决方案,因为它将处理找到的任何标记,并仅比较文本内容。
findDiff()
将找到差异,并使用输出和不同单词数组作为参数调用回调函数

JSFiddle:

但是,该解决方案存在一些局限性

  • 它假定pdf中的所有内容都存在于HTML文本中
  • 它只处理
    和空格,如果有其他可能的分隔符,例如制表符,则需要额外的代码
  • 它假定所有标记都是格式良好的,并且文本内容之间不会有结束标记(如果需要,应该改用
  • 该功能是一个简化的解决方案,未经过充分测试。您不能指望它提供任何保修,需要进行一些调整。我建议只提供
    正文
    中的内容,甚至更窄的范围,而不是整个HTML文件(如果可能的话),因为HTML文件的内容会有太多变化

  • 为什么不去掉html标记,只比较纯文本呢?这不起作用,因为pdf文本的位置可能与html文本相隔几行,因此不匹配,我已经尝试过了,html文本还有一个额外的部分。提供的html包含大量css、javascript标记、内联javascript、元标记和html注释。所以,如果你想保存它们并进行比较,那就不可能创建一些自动算法来实现。因此,首先,您必须指定要比较的内容,因为在这种情况下比较
    没有意义忽略脚本标记,只关注标记,因此html标记和内联CSW是您在“尝试剥离标记和比较”中提到的额外部分。它并没有真正发现差异并对其进行标记。原始问题已经修改了几次。他删除了他想要修改pdf的原始HTML部分。如果您真的想知道原始HTML及其区别,您可以查看我们在这里讨论的聊天室。您会注意到向其中添加HTML标记是多么不可能。我说服他去掉所有不必要的html标签,如等等。谢谢,我认为由于局限性,我实际上无法比较它们,只能得到html格式的PDF文本,但这对meI不起作用。我只是为输出空html标记获得了大量空白。不适用于fiddle中的简单示例说,一切都不同,甚至不会显示output@AK0101很抱歉
    parsePDFToken()
    中有一个bug,我没有注意到第一个字符是空格和/或有连续空格的情况。我已经修改并制作了一个新版本:在你的演示示例中,我仍然获得了一半的输出,并且有很多不同之处。输出在“为什么下载”处停止
    var s = "Hello everyone on stackoverflow";
    
    var y = "<html><head><head><body><div>Hello<span>everyone</span>on stackoverflow</div></body></html>";
    
    //using regular expressions match HTML tags and replace them with empty string. Make sure to trim the output so that the extra whitespaces at either end are removed.
    var z = y.replace(/(<([^>]+)>)/ig, ' ').trim();
    
    //compare if the stripped string matches the other string.
    if(z == s) {
        s = y;  
    }
    alert(s);
    
    /**
     * Parse and construct an Array of PDF text tokens
     * @params {string} text   The PDF text to be parsed
     * @return {object}         The parsed Array of tokens
     */
    function parsePDFText(text) {
        var token = text.split(' ');
        for (var i=0,l=token.length; i<l; i++) {
            // remove token of first space and consecutive space
            if (token[i] == '') {
                token.splice(i, 1);
            }
        }
        return token;
    }
    
    /**
     * Return the minimum indexOf among all the arguments
     * @params {...number} index  The indexOf
     * @return {number}           The minimum indexOf, -1 if all arguments are -1
     */
    function findMinIndex() {
        var min;
        for (var i = 0, l = arguments.length; i < l; i++) {
            // indexOf() returns -1 if not found
            if (arguments[i] === -1) {
                continue;
            }
            if (typeof min === 'undefined' || arguments[i] < min) {
                min = arguments[i];
            }
        }
        return min || -1;
    }
    
    /**
     * Parse and construct an Array of HTML tokens
     * @params {string} text   The HTML text to be parsed
     * @return {object}       The parsed Array of tokens
     */
    function parseHTMLText(text) {
        var currentIndex = 0,
            tl = text.length,
            tokens = [],
            token, firstChar, endPos;
        while (currentIndex < tl) {
            // determine the next token type
            firstChar = text.charAt(currentIndex);
            if (firstChar == '<') {
                // a tag
                // find the position of closing tag, assume all tags are well formed
                endPos = text.indexOf('>', currentIndex + 1) + 1;
                token = {
                    type: 'tag',
                    content: text.slice(currentIndex, endPos), 
                    valid: true
                }
                currentIndex = endPos;
            } else if (firstChar == ' ') {
                // a space
                token = {
                    type: 'space', 
                    content: ' ', 
                    valid: true
                }
                currentIndex++;
            } else {
                // a character, possibliy part of a word
                // find the end of the word
                // assume a word is delimitered either by tags or space
                endPos = findMinIndex(text.indexOf('<', currentIndex), text.indexOf(' ', currentIndex));
                // endPos is `-1` if there are not delimiter anymore, end of string reached
                if (endPos === -1) {
                    endPos = tl;
                }
                token = {
                    type: 'text',
                    content: text.slice(currentIndex, endPos), 
                    valid: true
                }
                currentIndex = endPos;
            }
            tokens.push(token);
        }
        return tokens;
    }
    
    /**
     * Find the difference between pdf text and html text and pass the output and differenc to a callback function
     * @params {string} pdfText     The pdf text
     * @params {string} htmlText    The html text
     * @params {function} callback  The callback function
     */
    function findDiff(pdfText, htmlText, callback) {
        var output = '', // the final output
            diff = [], // the array of different words
            pdfTokens = parsePDFText(pdfText),
            htmlTokens = parseHTMLText(htmlText), 
            j=0, hl=htmlTokens.length;
        // the pdf text is the reference point, i.e. all the words in pdf text should always be present in html text as well
        for (var i=0,pl=pdfTokens.length; i<pl; i++) {
            // find the first occurrence of the pdf text
            for(; j<hl; j++) {
                if (htmlTokens[j].type != 'text') {
                    // exclude comparison to non-text
                    continue;
                }
                // check if the two text matches
                if (htmlTokens[j].content == pdfTokens[i]) {
                    // a match is found
                    j++;
                    break;
                } else {
                    // push the different html token into `diff` array
                    diff.push(htmlTokens[j].content);
                    // set the `valid` field of token to false
                    htmlTokens[j].valid = false;
                }
            }
        }
        // invalidate the rest of the html text
        for(; j<hl; j++) {
            if (htmlTokens[j].type == 'text') {
                htmlTokens[j].valid = false;
            }
        }
        // concat the final string to output
        for (j=0; j<hl; j++) {
            if (htmlTokens[j].valid) {
                output += htmlTokens[j].content;
            }
        }
        callback(output, diff);
    }
    
    findDiff(text1, text2, function(output, diff) {
        console.log(output);
        console.log(diff);
    });