We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Split Images and Links

Now that we have the extraction functions, we will need to be able to split raw markdown text into TextNodes based on images and links.

Assignment

  • def split_nodes_image(old_nodes: list[TextNode]) -> list[TextNode]:
  • def split_nodes_link(old_nodes: list[TextNode]) -> list[TextNode]:

They should behave very similarly to split_nodes_delimiter, but obviously don't need a delimiter or a text type as input, because they always operate on images or links respectively. Here's some example usage:

node = TextNode(
    "This is text with a link [to boot dev](https://www.boot.dev) and [to youtube](https://www.youtube.com/@bootdotdev)",
    TextType.TEXT,
)
new_nodes = split_nodes_link([node])
# [
#     TextNode("This is text with a link ", TextType.TEXT),
#     TextNode("to boot dev", TextType.LINK, "https://www.boot.dev"),
#     TextNode(" and ", TextType.TEXT),
#     TextNode(
#         "to youtube", TextType.LINK, "https://www.youtube.com/@bootdotdev"
#     ),
# ]
def test_split_images(self):
    node = TextNode(
        "This is text with an ![image](https://i.imgur.com/zjjcJKZ.png) and another ![second image](https://i.imgur.com/3elNhQu.png)",
        TextType.TEXT,
    )
    new_nodes = split_nodes_image([node])
    self.assertListEqual(
        [
            TextNode("This is text with an ", TextType.TEXT),
            TextNode("image", TextType.IMAGE, "https://i.imgur.com/zjjcJKZ.png"),
            TextNode(" and another ", TextType.TEXT),
            TextNode("second image", TextType.IMAGE, "https://i.imgur.com/3elNhQu.png"),
        ],
        new_nodes,
    )

Run and submit the CLI tests from the root of the project.

Tips

Here are some spoilers that might help you out:

  • Make use of the extraction functions we wrote
  • If there are no images or links respectively, just return a list with the original TextNode in it
  • Don't append any TextNodes that have empty text to the final list
  • Your split_nodes_image and split_nodes_link functions will be very similar. You can try to share code between them if you want, but I was a copy/paste grug dev for this step.
  • You can use the .split() method with large strings as the delimiter, and it has an optional second "maxsplits" parameter, which you can set to 1 if you only want to split the string once at most. For each image extracted from the text, I split the text before and after the image markdown. For example:
sections = original_text.split(f"![{image_alt}]({image_link})", 1)