我在使用正则表达式将文本转换为标签时遇到问题

时间:2019-08-12 12:54:18

标签: javascript regex replace gridsome

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

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.

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

[the basics of content modelling](https://www.contentful.com/r/knowledgebase/content-modelling-basics/ "the basics of content modelling")

从此文本中替换为链接a

并插入html标签

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

我正在使用该正则表达式

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

1 个答案:

答案 0 :(得分: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)