UNPKG

1.51 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 closingParenIndex =
37 balancedMatch('(', ')', lowerCaseSource.slice(openingParenIndex)).end + openingParenIndex;
38 const argumentsLength = closingParenIndex - openingParenIndex - 1;
39
40 result =
41 result.slice(0, openingParenIndex + 1) +
42 blurChar.repeat(argumentsLength) +
43 result.slice(closingParenIndex);
44 searchStartIndex = closingParenIndex;
45 }
46
47 return result;
48};