【问题标题】:I'm having trouble converting text into a tag with regex我无法使用正则表达式将文本转换为标签
【发布时间】:2019-12-19 01:23:34
【问题描述】:

我的 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/ "文档"),了解有关如何使用 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

【问题讨论】:

  • 如果您创建 JSFiddle 并与我们分享该链接,我们将更容易为您提供帮助。

标签: javascript regex replace gridsome


【解决方案1】:

您的模式缺少 () 在引号中包含 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)

【讨论】:

  • 非常感谢,没那么难,我还要多学习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2016-03-25
  • 2014-05-24
  • 2014-08-28
  • 1970-01-01
相关资源
最近更新 更多