1. function transformHTMLData(htmlString) {
  2. try {
  3. const parser = new DOMParser();
  4. const doc = parser.parseFromString(htmlString, 'text/html');
  5. const data = [];
  6. // Hardcoded limits - adjust as needed
  7. const maxItems = 100;
  8. const maxTextLength = 200;
  9. const elements = doc.querySelectorAll('div'); // Example: process all divs
  10. let itemCount = 0;
  11. for (const element of elements) {
  12. const textContent = element.textContent.trim();
  13. if (textContent.length > maxTextLength) {
  14. textContent = textContent.substring(0, maxTextLength) + "..."; // Truncate long text
  15. }
  16. // Create a data object
  17. const dataItem = {
  18. id: ++ itemCount, // Simple ID
  19. name: textContent, // Use the text content as the name
  20. // Add other fields as needed - can be derived from element attributes
  21. };
  22. data.push(dataItem);
  23. if (data.length >= maxItems) {
  24. console.warn("Reached maximum items limit. Stopping processing.");
  25. break; // Stop processing if limit reached
  26. }
  27. }
  28. return JSON.stringify(data, null, 2); // Convert to JSON with indentation
  29. } catch (error) {
  30. console.error("Error transforming HTML:", error);
  31. return JSON.stringify({ error: "Transformation failed" }, null, 2);
  32. }
  33. }

Add your comment