UNPKG

1.62 kBJavaScriptView Raw
1'use strict';
2
3const balancedMatch = require('balanced-match');
4
5/**
6 * Replace all of the characters that are arguments to a certain
7 * CSS function with some innocuous character.
8 *
9 * This is useful if you need to use a RegExp to find a string
10 * but want to ignore matches in certain functions (e.g. `url()`,
11 * which might contain all kinds of false positives).
12 *
13 * For example:
14 * blurFunctionArguments("abc url(abc) abc", "url") === "abc url(```) abc"
15 *
16 * @param {string} source
17 * @param {string} functionName
18 * @return {string} - The result string, with the function arguments "blurred"
19 */
20module.exports = function (source, functionName, blurChar = '`') {
21 const nameWithParen = `${functionName.toLowerCase()}(`;
22 const lowerCaseSource = source.toLowerCase();
23
24 if (!lowerCaseSource.includes(nameWithParen)) {
25 return source;
26 }
27
28 const functionNameLength = functionName.length;
29
30 let result = source;
31 let searchStartIndex = 0;
32
33 while (lowerCaseSource.includes(nameWithParen, searchStartIndex)) {
34 const openingParenIndex =
35 lowerCaseSource.indexOf(nameWithParen, searchStartIndex) + functionNameLength;
36 const parensMatch = balancedMatch('(', ')', lowerCaseSource.slice(openingParenIndex));
37
38 if (!parensMatch) {
39 throw new Error(`No parens match: "${source}"`);
40 }
41
42 const closingParenIndex = parensMatch.end + openingParenIndex;
43 const argumentsLength = closingParenIndex - openingParenIndex - 1;
44
45 result =
46 result.slice(0, openingParenIndex + 1) +
47 blurChar.repeat(argumentsLength) +
48 result.slice(closingParenIndex);
49 searchStartIndex = closingParenIndex;
50 }
51
52 return result;
53};