Search code examples
javascriptreactjsstylesscript-tag

Truncate <style> tag data from a string


I have a string let's say headData which is combination of <script> and <style> tags. For Ex(with Dummy data) -

let headData = '<style>
        @font-face {
            font-family: 'Roboto';
            font-style: normal;
            font-weight: 300;
            src: local('Roboto Light'), local('Roboto-Light'), url(path-to.woff) format('woff');
        }</style>
    <script>var isPresent = false;</script>
    <script>var isContent = true;</script>
    <style>@font-face {
            font-family: 'Courgette';
            font-style: normal;
            font-weight: 400;
            src: local('Courgette Regular'), local('Courgette-Regular'), url(path-to.woff2) format('woff2');}</style>'

I inject whole of headData in tag like below.

<script dangerouslySetInnerHTML={{__html: headData}} />

I don't want to inject <style> tag related data and only want all the <script> tag related data to be injected.

So what I finally want to inject is similar to -

let headData = '<script>var isPresent = false;</script>
        <script>var isContent = true;</script>'

What is the right way to achieve this in Javascript?


Solution

  • You can use RegEx with Capturing Groups to replace the style tag and it's content for all occurrences:

    /(<style>)[^<>]*(<\/style>)/g
    

    Where:

    (<style>) - 1st Capturing Group

    <style> matches the characters <style> literally (case sensitive)

    [^<>]* match a single character not present in the following

    1. * Quantifier matches between zero and unlimited times, as many times as possible

    2. <> matches a single character in the list <>

    (<\/style>) - 2nd Capturing Group

    g global modifier. Matches all(doesn't return after first match)

    Demo:

    let headData = `<style>
            @font-face {
                font-family: 'Roboto';
                font-style: normal;
                font-weight: 300;
                src: local('Roboto Light'), local('Roboto-Light'), url(path-to.woff) format('woff');
            }</style>
        <script>var isPresent = false;<\/script>
        <script>var isContent = true;<\/script>
        <style>@font-face {
                font-family: 'Courgette';
                font-style: normal;
                font-weight: 400;
                src: local('Courgette Regular'), local('Courgette-Regular'), url(path-to.woff2) format('woff2');}</style>`;
                
     var re = /(<style>)[^<>]*(<\/style>)/g;
     headData = headData.replace(re,'').trim();
     console.log(headData);