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