remove_markdown_links/
lib.rs

1/// Replaces Markdown links in the input text with just the text.
2///
3/// # Arguments
4///
5/// * `input` - A string slice that contains Markdown text with links.
6///
7/// # Returns
8///
9/// A string with Markdown links replaced by their corresponding text.
10///
11/// # Examples
12///
13/// ```
14/// use remove_markdown_links::remove_markdown_links;
15/// let markdown = "This is a [link](https://www.example.com) to Example.".to_string();
16/// let result = remove_markdown_links(&markdown);
17/// assert_eq!(result, "This is a link to Example.");
18/// ```
19pub fn remove_markdown_links(input: &str) -> String {
20    let re = regex::Regex::new(r"\[([^\[\]]+)\]\(([^)]+)\)").unwrap();
21    let replaced = re.replace_all(input, |caps: &regex::Captures| {
22        caps.get(1).unwrap().as_str().to_string()
23    });
24    replaced.to_string()
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    #[test]
32    fn test_no_links() {
33        let input_string = "Hello, World!".to_string();
34        let expected_result = input_string.clone();
35
36        let result = remove_markdown_links(&input_string);
37        assert_eq!(result, expected_result);
38    }
39
40    #[test]
41    fn test_remove_markdown_link() {
42        let input_string = "Hello, [World](https://example.com/)!".to_string();
43        let expected_result = "Hello, World!".to_string();
44
45        let result = remove_markdown_links(&input_string);
46        assert_eq!(result, expected_result);
47    }
48
49    #[test]
50    fn test_remove_multiple_markdown_links() {
51        let input_string =
52            "Hello, [World](https://example.com/)! How is it [going](https://en.wikipedia.org/)!"
53                .to_string();
54        let expected_result = "Hello, World! How is it going!".to_string();
55
56        let result = remove_markdown_links(&input_string);
57        assert_eq!(result, expected_result);
58    }
59}