CharlieBBS

True_AGI_Believer
True_AGI_Believer

Posted on

Reddit 偷贴机,输入帖子网址自动转 Markdown

<!DOCTYPE html>
<form id="jsonForm" style="display: flex;">
    <input type="text" id="jsonURL" placeholder="Enter Reddit post URL here" style="width: 100%;">
    <input type="submit" value="Submit">
    <button id="copyButton">Copy</button>
</form>

<div id="selftext"></div>
<script src="https://cdn.jsdelivr.net/npm/showdown@latest/dist/showdown.min.js"></script>
<script>
    const converter = new showdown.Converter()
    let selftext = ''

    function decodeHTML(html) {
        const doc = new DOMParser().parseFromString(html, "text/html")
        return doc.documentElement.textContent
    }

    function convertToMarkdownImgFormat(str) {
        const regex = /(https?:\/\/[^ ?]*\.(?:png|jpg|jpeg|gif)(?:\?\S*)?)/g
        return str.replace(regex, '![]($1)')
    }

    document.getElementById('jsonForm').addEventListener('submit', function (e) {
        e.preventDefault()
        const url = document.getElementById('jsonURL').value + '/.json'
        fetch(url)
            .then(response => response.json())
            .then(data => {
                selftext = data[0].data.children[0].data.selftext
                selftext = decodeHTML(selftext)
                selftext = convertToMarkdownImgFormat(selftext)
                document.getElementById('selftext').innerHTML = converter.makeHtml(selftext)
            })
            .catch(alert)
    })

    document.getElementById('copyButton').addEventListener('click', function(e) {
        e.preventDefault()
        const copyText = document.getElementById("selftext")
        navigator.clipboard.writeText(selftext)
        .then(() => {
            this.innerText = 'Copied!'
            setTimeout(() => { this.innerText = 'Copy' }, 500)
        })
        .catch(alert)
    })
</script>
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
true_agi_believer profile image
True_AGI_Believer Author

点击 "Submit" 启动偷贴,网页上会出现 Markdown 渲染效果预览,然后点击 "Copy" 按钮来复制 Markdown 代码
这段代码 100% 都是 GPT-4 写的,本来这个偷贴机几个小时前就写好了,但发布前对 UI 样式不满意,身边又没有设备可以登录 ChatGPT,看着代码脑子里就是一片空白,还好找到 Sydney 改好了