1

我的 div.content 中有一个示例文本

这是您的第一个 Contentful 内容,使用 [Content Delivery API](https://www.contentful.com/developers/docs/references/content-delivery-api/“Content Delivery API”)以 JSON 格式提取。
内容和演示现在已解耦,让您可以集中精力构建完美的应用程序。
## 你的第一步 使用 Contentful 进行构建很容易。先花点时间了解一下【内容建模基础知识】(https://www.contentful.com/r/knowledgebase/content-modelling-basics/《内容建模基础知识》),可以在[内容网络应用](https://app.contentful.com/“内容网络应用”)。
一旦你明白了,请随时访问 [文档](https://www.contentful.com/developers/docs/ "Documentation"),了解更多关于如何使用 Contentful 构建应用程序的信息,尤其是[API 基础](https://www.contentful.com/developers/docs/concepts/apis/《API 基础》) 以及我们的四个 API 中的每一个,如下图所示。

我想得到这样的所有字符串:

【内容建模基础】(https://www.contentful.com/r/knowledgebase/content-modelling-basics/《内容建模基础》)

从此文本中替换它们为链接 a

并插入一个html标签

<a href="https://www.contentful.com/r/knowledgebase/content-modelling-basics/ ">the basics of content modelling</a>

我正在使用那个正则表达式

let pattern = /\[(.*?)\]\((.*?)\)/gmi
4

1 回答 1

3

缺少()包含 URL 和引号中的字符串的模式。添加\s\".*?\"到您的模式 -\s匹配空格,如果您想在 URL 末尾留空格,可以省略它

let pattern = /\[(.*?)\]\((.*?)\s\".*?\"\)/gm;

let text = `These is your very first content with Contentful, pulled in JSON format using the [Content Delivery API](https://www.contentful.com/developers/docs/references/content-delivery-api/ "Content Delivery API").
 Content and presentation are now decoupled, allowing you to focus your efforts in building the perfect app.


## Your first steps

Building with Contentful is easy. First take a moment to get [the basics of content modelling](https://www.contentful.com/r/knowledgebase/content-modelling-basics/ "the basics of content modelling"), which you can set up in the [Contentful Web app](https://app.contentful.com/ "Contentful Web app"). 
Once you get that, feel free to drop by the [Documentation](https://www.contentful.com/developers/docs/ "Documentation") to learn a bit more about how to build your app with Contentful, in particular the [API basics](https://www.contentful.com/developers/docs/concepts/apis/ "API basics") and each one of our four APIs, as shown below.`

let result = text.replace(pattern, '<a href="$2">$1</a>')

console.log(result)

于 2019-08-12T13:12:32.383 回答