Skip to content

Commit fefe009

Browse files
committed
add HTML.toText()
1 parent 433919b commit fefe009

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

src/javaforce/HTML.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
public class HTML {
1111

12+
public static final boolean debug = false;
13+
1214
/** Generate html.form.input
1315
* @param name = element name (optional)
1416
* @param id = element id (optional)
@@ -143,4 +145,45 @@ public static String addJSfile(String file) {
143145
public static String addJSinline(String script) {
144146
return "<script>" + script + "</script>";
145147
}
148+
149+
/** Converts HTML to text/plain. */
150+
public static String toText(String html) {
151+
StringBuilder txt = new StringBuilder();
152+
int html_len = html.length();
153+
if (debug) JFLog.log("len=" + html_len);
154+
int html_off = 0;
155+
while (html_off < html_len) {
156+
int i1 = html.indexOf('<', html_off);
157+
if (debug) JFLog.log("i1=" + i1);
158+
if (i1 == -1) {
159+
txt.append(html.substring(html_off, html_len - html_off));
160+
html_off = html_len;
161+
} else {
162+
if (i1 > 0) {
163+
if (debug) JFLog.log("substring=" + html_off + "," + i1);
164+
txt.append(html.substring(html_off, i1));
165+
}
166+
int i2 = html.indexOf('>', i1);
167+
if (debug) JFLog.log("i2=" + i2);
168+
if (i2 == -1) {
169+
JFLog.log("HTML.toText() : tag left open");
170+
break;
171+
} else {
172+
String tag = html.substring(i1 + 1, i2);
173+
switch (tag) {
174+
case "br": txt.append("\r\n"); break;
175+
}
176+
html_off = i2 + 1;
177+
}
178+
}
179+
}
180+
return txt.toString();
181+
}
182+
183+
public static void main(String[] args) {
184+
String html = "<h1>This is HTML</h1><br>Converted to text!<br>";
185+
System.out.println(html);
186+
String txt = toText(html);
187+
System.out.println(txt);
188+
}
146189
}

0 commit comments

Comments
 (0)