Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Implemented TextNode.splitText

  • Loading branch information...
commit e3ddbb8db9977fe139bb2fdf8f22166263745235 1 parent 096e130
@jhy jhy authored
View
22 src/main/java/org/jsoup/nodes/TextNode.java
@@ -1,6 +1,7 @@
package org.jsoup.nodes;
import org.jsoup.helper.StringUtil;
+import org.jsoup.helper.Validate;
/**
A text node.
@@ -60,7 +61,6 @@ public String getWholeText() {
return attributes == null ? text : attributes.get(TEXT_KEY);
}
-
/**
Test if this text node is blank -- that is, empty or only whitespace (including newlines).
@return true if this document is empty or only whitespace, false if it contains any text content.
@@ -69,6 +69,26 @@ public boolean isBlank() {
return StringUtil.isBlank(getWholeText());
}
+ /**
+ * Split this text node into two nodes at the specified string offset. After splitting, this node will contain the
+ * original text up to the offset, and will have a new text node sibling containing the text after the offset.
+ * @param offset string offset point to split node at.
+ * @return the newly created text node containing the text after the offset.
+ */
+ public TextNode splitText(int offset) {
+ Validate.isTrue(offset >= 0, "Split offset must be not be negative");
+ Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length");
+
+ String head = getWholeText().substring(0, offset);
+ String tail = getWholeText().substring(offset);
+ text(head);
+ TextNode tailNode = new TextNode(tail, this.baseUri());
+ if (parent() != null)
+ parent().addChildren(siblingIndex()+1, tailNode);
+
+ return tailNode;
+ }
+
void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) {
String html = Entities.escape(getWholeText(), out);
if (out.prettyPrint() && parent() instanceof Element && !((Element) parent()).preserveWhitespace()) {
View
12 src/test/java/org/jsoup/nodes/TextNodeTest.java
@@ -44,4 +44,16 @@
assertEquals("kablam &", tn.text());
assertEquals("One <span>two &amp;</span>kablam &amp;", TextUtil.stripNewlines(p.html()));
}
+
+ @Test public void testSplitText() {
+ Document doc = Jsoup.parse("<div>Hello there</div>");
+ Element div = doc.select("div").first();
+ TextNode tn = (TextNode) div.childNode(0);
+ TextNode tail = tn.splitText(6);
+ assertEquals("Hello ", tn.getWholeText());
+ assertEquals("there", tail.getWholeText());
+ tail.text("there!");
+ assertEquals("Hello there!", div.text());
+ assertTrue(tn.parent() == tail.parent());
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.