YouTip LogoYouTip

Met Cdata Substringdata

## XML DOM substringData() Method The `substringData()` method is a built-in XML DOM function used to extract a specific substring from a `CDATASection` node (or other character data nodes like `Text` and `Comment`). This method is highly useful when you need to parse, slice, or manipulate large blocks of text or markup enclosed within CDATA sections without modifying the original node data. --- ## Syntax ```javascript cdataNode.substringData(offset, count); ``` ### Parameters | Parameter | Type | Required / Optional | Description | | :--- | :--- | :--- | :--- | | `offset` | `Number` | **Required** | The zero-based starting index from which to begin extracting characters. | | `count` | `Number` | **Required** | The number of characters to extract. | ### Return Value * **Type:** `String` * **Description:** Returns a new string containing the extracted characters. If the sum of `offset` and `count` exceeds the total length of the data, the method returns all characters from the `offset` to the end of the data. --- ## Code Example The following example demonstrates how to load an XML document (`books_cdata.xml`) and extract a specific substring from its first CDATA section. ### Sample XML File (`books_cdata.xml`) Assume we have an XML file containing HTML markup inside a CDATA section: ```xml Stunning!]]> ``` ### JavaScript Implementation ```javascript // Load the XML document const xmlDoc = loadXMLDoc("books_cdata.xml"); // Access the first element's child node (the CDATA section) const cdataNode = xmlDoc.getElementsByTagName("html").childNodes; // Extract 4 characters starting from index 3 ("Stun") const substringResult = cdataNode.substringData(3, 4); // Output the original CDATA content document.write("Original CDATA: " + cdataNode.nodeValue); document.write("
"); // Output the extracted substring document.write("Extracted Substring: " + substringResult); ``` ### Output ```text Original CDATA: Stunning! Extracted Substring: Stun ``` --- ## Considerations & Best Practices 1. **Zero-Based Indexing:** Like standard JavaScript string methods, the `offset` parameter is zero-based. The first character of the CDATA section is at index `0`. 2. **Exception Handling:** * If `offset` is negative or greater than the total character length of the node, an `INDEX_SIZE_ERR` DOMException is thrown. * If `count` is negative, a DOMException is thrown. 3. **Performance:** The `substringData()` method does not modify the original node. It returns a copy of the specified range, making it safe to use for read-only operations. 4. **Alternative in Modern JS:** If you have already extracted the node's text content via `nodeValue` or `data`, you can also use standard JavaScript string manipulation methods like `substring()` or `slice()`: ```javascript const text = cdataNode.nodeValue; const result = text.substring(3, 7); // Equivalent to substringData(3, 4) ```
← Soap IntroMet Cdata Splittext β†’