简体   繁体   中英

JS regex to replace empty lines within SCSS between closing curly brace and opening class/id

I am trying to create a regex to replace empty lines between SCSS rulesets. The regex should match from a closing curly brace up to either a class (.) or id (#) and remove any lines. Any empty lines which are not placed between these identifyers should not be affected, including if there is something like a comment in the middle as well.

I have setup a fiddle which can be used to test the below example: https://jsfiddle.net/9y33cvtg/2/

Example:

BEFORE

// START

.test1 {
    background: #FFFFFF;

    .test2 {
        background: #FFFFFF;

        .test3 {
            background: #FFFFFF;
        }
    }
}

.test5 {
    background: #FFFFFF;
}

.test6 {
    background: #FFFFFF;
}

// Comment

.test7 {
    background: #FFFFFF;
}

AFTER:

// START

.test1 {
    background: #FFFFFF;

    .test2 {
        background: #FFFFFF;

        .test3 {
            background: #FFFFFF;
        }
    }
}
.test5 {
    background: #FFFFFF;
}
.test6 {
    background: #FFFFFF;
}

// Comment

.test7 {
    background: #FFFFFF;
}

So far I have tried to use the following but it has not worked:

str.replace(/\}(.*?)\./g, '')

Parsing CSS files should be done with dedicated libraries.

The following solution is only going to do the following: it will detect a line that equals } followed with 1 or more whitespace chars up to a line that starts with a dot. Use it at your own risk.

.replace(/^}$\s+^\.\b/gm, '}\n.')

See the regex demo .

Details

  • ^ - start of a line (due to the m modifier)
  • } - a }
  • $ - end of a line
  • \\s+ - 1 or more whitespaces
  • ^ - start of a line
  • \\. - a dot (note: if you want to make sure it is followed with some word char, you may use \\b or even \\w )

Below is a JS demo:

 var str = document.querySelector('.string').innerText; var output = document.querySelector('.output'); output.innerText = str.replace(/^}$\\s+^\\.\\b/gm, '}\\n.');
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <strong>Input:</strong> <pre class="string"> // START .test1 { background: #FFFFFF; .test2 { background: #FFFFFF; .test3 { background: #FFFFFF; } } } .test5 { background: #FFFFFF; } .test6 { background: #FFFFFF; } // Comment .test7 { background: #FFFFFF; } </pre> <br> <strong>Output:</strong> <pre class="output"> </pre>

Hello you need to catch line break like this :

output.innerText = str.replace(/^}[\r\n]{2,}(?!\/\/)/gm, '}\n');

it seems to works, tell me if it solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM