【问题标题】:JavaScript String replace second occurrence in XMLJavaScript 字符串替换 XML 中的第二次出现
【发布时间】:2019-11-05 13:57:24
【问题描述】:

你好有以下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 标记的第二次出现。所以基本上用空格替换出现在&lt;books&gt;开始标签之后的&lt;?xml version="1.0" encoding="UTF-8"?&gt;字符串。

有什么建议吗?我尝试了其他链接,但无法获得有效的解决方案。问题是在 xml 标记和字符串替换函数之间有 ", ? and &gt; 将其视为转义序列字符。

这是我尝试过的:

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);

上面仍然打印两个 xml 标签

【问题讨论】:

标签: javascript xml string


【解决方案1】:

假设您的 XML 总是这样,您可以使用常规的 String 方法来查找字符串的最后一次出现并通过在其周围创建 XML 的子字符串来删除它:

 const 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>`;
const strToReplace = '<?xml version="1.0" encoding="UTF-8"?>';
const index = xml.lastIndexOf(strToReplace);

// The new left- and right-sides of the string will omit the strToReplace
const newXml = xml.substring(0, index) + xml.substring(index + strToReplace.length);
console.log(newXml);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2022-10-07
    • 2019-07-02
    • 2014-02-13
    相关资源
    最近更新 更多