如何删除 <script></script> 标签之间的文本

San*_*nto 5 html java html-parsing

我想删除标签之间的内容<script></script>。我正在手动检查模式并iterating使用 while 循环。但是,我正在了解StringOutOfBoundException这一行:

String script = source.substring(startIndex,endIndex-startIndex);
Run Code Online (Sandbox Code Playgroud)

下面是完整的方法:

String script = source.substring(startIndex,endIndex-startIndex);
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么吗?我正在得到endIndex=-1。任何人都可以帮助我确定为什么我的代码被破坏。

Aka*_*ngh 3

String text = "<script>This is dummy text to remove </script> dont remove this";
    StringBuilder sb = new StringBuilder(text);
    String startTag = "<script>";
    String endTag = "</script>";

    //removing the text between script
    sb.replace(text.indexOf(startTag) + startTag.length(), text.indexOf(endTag), "");

    System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)

如果您也想删除脚本标签,请添加以下行:

sb.toString().replace(startTag, "").replace(endTag, "")
Run Code Online (Sandbox Code Playgroud)

更新

如果你不想使用StringBuilder你可以这样做:

    String text = "<script>This is dummy text to remove </script> dont remove this";
    String startTag = "<script>";
    String endTag = "</script>";

    //removing the text between script
    String textToRemove = text.substring(text.indexOf(startTag) + startTag.length(), text.indexOf(endTag));
    text = text.replace(textToRemove, "");

    System.out.println(text);
Run Code Online (Sandbox Code Playgroud)