Search code examples
javascripthtmlcssjsonreddit

reformat characters in json data


I am retrieving data from reddit json. and some data is like that:

The actual resolution of this image is 3067x2276, not 4381x3251. See [this](https://www.reddit.com/r/EarthPorn/wiki/index#wiki_resolution.3F_what_is_that_and_how_can_i_find_it.3F) page for information on how to find out what the resolution of an image is.

i want to insert the data into <p></p> on my page but the link is as it is above (not clickable).

Notice when i try to post it on stackoverflow, it very nicely reformats into a clickable link. How do i do that?

reformatted by stackoverflow:

The actual resolution of this image is 3067x2276, not 4381x3251. See this page for information on how to find out what the resolution of an image is.

How do i achieve that?


Solution

  • I feel like I cheated, but inspecting the OP in my browser, I get...

    <p>The actual resolution of this image is 3067x2276, not 4381x3251. See <a href="https://www.reddit.com/r/EarthPorn/wiki/index#wiki_resolution.3F_what_is_that_and_how_can_i_find_it.3F" rel="nofollow noreferrer">this</a> page for information on how to find out what the resolution of an image is.</p>
    

    In other words, if you find [words](URL), replace it with:

    <a href="URL">words</a>
    

    This little regex tries to capture the contents of [] followed by (). Checking for http may be insufficient depending on the sort of links you expect...

    let regex = /\[(.*?)\]\(([^\)]+)\)/g;
    let matches = regex.exec(line);
    // matches ought to contains words and a potential url
    if (matches.length > 2 && matches[2].startsWith("http://")) {
        // matches[2] is probably a url, so...
        let replace = `<a href="${matches[2]}">${matches[1]}</a>`
        // ...
    }