Search code examples
javascriptregexreplacegridsome

I'm having trouble converting text into a tag with regex


I have a sample text in my 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.

I want to get all the strings like this:

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

from this text and replace them with link a

and insert in a html tags

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

I am using that regex

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

Solution

  • Your pattern is missing that () contains both URL and string in quotes. Add \s\".*?\" to your pattern - \s matches whitespace, you can omit it if you want to leave space at the end of 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)