JavaScript字符串替换XML中的第二个匹配项
Hi具有以下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"?> <Fiction> <tt:Author>A</tt
<?xml version="1.0" encoding="UTF-8"?>
<library>
<item>
<books>
<?xml version="1.0" encoding="UTF-8"?>
<Fiction>
<tt:Author>A</tt:Author>
<tt:BookName>45</tt:BookName>
</Fiction>
</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);