Finding the missing sequence number in a file

十年热恋 提交于 2019-12-13 05:43:34

问题


Hi I have to find a missing number in an xml file. but I feel difficulty to find. Pls suggest some ideas.

Example

A file contains an <a> tag which include id i.e page-1,2... I need to find the missing numbers using jquery.

a.xml


<p>have a great <a id="page-1"/>day. How are you.</p>
<p><a id="page-2"/>Have a nice day.</p>
<p>How <a id="page-5"/>are you</p>
<p>Life is so exciting<a id="page-6"/></p>

My code

<script>
    $(document).ready(function() {      
        $("#find").click(function(){
            Fname = $("#myFile").val();
            lpage = $("#lpage").val();

            $.get(Fname, function(data){
                var lines = data.split("\n");
                if (lines.match(id="page-)) { //how to use regular exoreessi0n
                    alert("hi");
                }
            });
        });
    });
</script>   

回答1:


I'll take some assumptions regarding your input. Please add validations as necessary:

var lines = ['<p>have a great <a id="page-1"/>day. How are you.</p>',
    '<p><a id="page-2"/>Have a nice day.</p>',
    '<p>How <a id="page-5"/>are you</p>',
    '<p>Life is so exciting<a id="page-6"/></p>'];

    var sequences = [];
    lines.forEach(function(line) {

        // Not efficient but simple
        // Let jQuery parse this string to object, so we won't need regexp
        var obj = $(line);

        // Assuming there's always A and ID attribute
        var id = obj.find("a").attr("id").split("-");

        // Assuming sequence is always last
        sequences.push(parseInt(id[id.length - 1]));
    });

    sequences.sort();

    // Again, inefficient, but will do the job
    var last = sequences[sequences.length - 1];

    for (var i = last; i >= 0; i--) {
        if (sequences.indexOf(i) < 0) {
            console.log(i + " is missing");
        }
    }


来源:https://stackoverflow.com/questions/40057381/finding-the-missing-sequence-number-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!