如何删除< script></script>之间的文本标签 [英] How to remove text between <script></script> tags
本文介绍了如何删除< script></script>之间的文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除< script></script>
标签之间的内容.我正在使用while循环手动检查模式和 iterating
.但是,我在这行得到 StringOutOfBoundException
:
I want to remove the content between <script></script>
tags. I'm manually checking for the pattern and iterating
using while loop. But, I'm getting StringOutOfBoundException
at this line:
String script = source.substring(startIndex,endIndex-startIndex);
下面是完整的方法:
public static String getHtmlWithoutScript(String source) {
String START_PATTERN = "<script>";
String END_PATTERN = " </script>";
while (source.contains(START_PATTERN)) {
int startIndex=source.lastIndexOf(START_PATTERN);
int endIndex=source.indexOf(END_PATTERN,startIndex);
String script=source.substring(startIndex,endIndex);
source.replace(script,"");
}
return source;
}
我在这里做错什么了吗?我正在得到 endIndex = -1
.谁能帮助我确定为什么我的代码被破坏了.
Am I doing anything wrong here? And I'm getting endIndex=-1
. Can anyone help me to identify, why my code is breaking.
推荐答案
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());
如果您也想删除脚本标签,请添加以下行:
If you want to remove the script tags too add the following line :
sb.toString().replace(startTag, "").replace(endTag, "")
更新:
如果您不想使用 StringBuilder
,则可以执行以下操作:
If you dont want to use StringBuilder
you can do this:
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);
这篇关于如何删除< script></script>之间的文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文