javascript - 如何将以特定模式开头的每一行传输到字符串的末尾?

标签 javascript regex

我有这样一个字符串:

var str = " this is a [link][1]
            [1]: http://example.com
            and this is a [good website][2] in my opinion
            [2]: http://goodwebsite.com
            [3]: http://example.com/fsadf.jpg
            [![this is a photo][3]][3]
            and there is some text hare ..! ";

现在我想要这个:

var newstr = "this is a [link][1]
              and this is a [good website][2] in my opinion
              [![this is a photo][3]][3]
              and there is some text hare ..!


                [1]: http://example.com
                [2]: http://goodwebsite.com
                [3]: http://example.com/fsadf.jpg"

我该怎么做?


实际上,那个变量 str 是一个 textarea 的值......我正在尝试创建一个 Markdown 编辑器......所以我想要的与 SO 的 textarea 所做的完全一样.


这是我的尝试:

/^(\[[0-9]*]:.*$)/g 选择 [any digit]: in the first of line

而且我认为我应该使用 () 为此创建一个组,然后将其替换为 \n\n $1

最佳答案

试试这个:

strLinksArray = str.match(/(\[\d+\]\:\s*[^\s\n]+)/g);
strWithoutLinks = str.replace(/(\[\d+\]\:\s*[^\s\n]+)/g, ''); //removed all links

在这里,您将获得没有链接的数组和字符串形式的链接,然后进行您想要的任何更改。

关于javascript - 如何将以特定模式开头的每一行传输到字符串的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940641/

相关文章:

javascript - 使用 Node 验证器从字符串中去除 HTML 标签

javascript - 如何在 Qualtrics 中使用自动移动受访者和具有多个分页符的 block 的全局计时器?

javascript - document.getElementById 返回 [object HTMLDivElement]

javascript - 如何让div在特定高度后淡入?

regex - 正则表达式匹配序言

Python 使用正则表达式提取 twitter 文本数据中的@user 和 url 链接

javascript - 正则表达式匹配特定字符串且不超过两个斜杠

javascript - 匹配字符串的正则表达式?

javascript - 使用 JQuery 避免重复下拉项(用于创建比较)

javascript - 为什么某些字符出现在 JS console.log 中的 'broken'?