Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.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字符串替换XML中的第二个匹配项_Javascript_Xml_String - Fatal编程技术网

JavaScript字符串替换XML中的第二个匹配项

JavaScript字符串替换XML中的第二个匹配项,javascript,xml,string,Javascript,Xml,String,Hi具有以下xml: <?xml version="1.0" encoding="UTF-8"?> <library> <item> <books> <?xml version="1.0" encoding="UTF-8"?> &lt;Fiction&gt; &lt;tt:Author&gt;A&lt;/tt

Hi具有以下xml:

<?xml version="1.0" encoding="UTF-8"?>
    <library>
    <item>
    <books> 
        <?xml version="1.0" encoding="UTF-8"?>
            &lt;Fiction&gt;
            &lt;tt:Author&gt;A&lt;/tt:Author&gt;
            &lt;tt:BookName&gt;45&lt;/tt:BookName&gt;
            &lt;/Fiction&gt;
    </books>
    </item>
    </library>

上面仍然打印两个xml标记

假设您的xml总是这样,您可以使用常规字符串方法查找字符串的最后一个匹配项,并通过在其周围创建xml的子字符串将其删除:

constxml=`
小说
tt:AuthorA/tt:Author
tt:BookName 45/tt:BookName
/虚构的
`;
常量strToReplace='';
const index=xml.lastIndexOf(strToReplace);
//字符串的新左侧和右侧将省略strToReplace
const newXml=xml.substring(0,index)+xml.substring(index+strToReplace.length);

log(newXml)此xml来自何处?它来自外部API。外部API未生成有效的xml。您应联系供应商并要求其纠正;你可以把他们指向@AndrewMorton,我认为这是不可能的。谢谢你的评论
var stringToReplace = '<?xml version="1.0" encoding="UTF-8"?>';
   var string = data.string;
   //console.log(string);
    var t=0;   
    var text = string.replace(/stringToReplace/g, function (match) {
    t++;

    return (t === 2) ? "Not found" : match;
    });
console.log(text);