Cwe
November 3, 2016, 2:48pm
1
Enonic version: 6.7.3
OS: Mac and Linux
These work in the browser console, but for some reason the do not work in an Enonic XP controller.
var test = "svg\r\n class=\"\n\rtestclass\r\n\"\n\r xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 212.6 186.12\"\n>".replace(/(class=)(["'])((?:(?=(\\?))\3[\S\s])*?)\2/, function(match, p1, p2, p3, offset, string) {return p1 + p2 + p3 + (p3.length ? ' ': '') + 'JALLA' + p2;});
log.info(`test:${test}`);
var test2 = "svg\r\n class=\"\n\rtestclass\r\n\"\n\r xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 212.6 186.12\"\n>".replace(/^(svg[\S\s]*?class=)(["'])((?:(?=(\\?))\3[\S\s])*?)\2([\S\s]*)/, "$1$2$3 JALLA$2$5");
log.info(`test2:${test2}`);
You can simplify to match(/…/), the replace is just for showing what I actually want to do.
Cwe
November 4, 2016, 8:16am
2
Ideas taken from:
Replacing [\s\S]
with (.|\r|\n)
or (.|[\r\n])
does not help.
Cwe
November 4, 2016, 9:03am
3
Went with this “workaround” instead:
const searchValue = 'class="';
const foundIndex = string.indexOf(searchValue);
if(foundIndex !== -1) {
string = string.slice(0, foundIndex) + searchValue + classesString + ' ' + string.slice(foundIndex + searchValue.length);
} else {
string = string.replace(/^svg/, `svg class="${classesString}"`);
}
gri
November 4, 2016, 2:10pm
4
I only tried the first regexp but there is something strange.
I do not understand your “\3”. It references the capturing group containing it. If you remove it, the regexp seems to work
Cwe
November 4, 2016, 2:14pm
5
I’m looking for balanced quotes (singles or doubles).
Which is why the second capture is reused to match the captured quote.
It’s possible the third capture snook in during experimentation, let me think about it.
Cwe
November 4, 2016, 2:18pm
6
javascript, regex
?=
Match a suffix but exclude it from capture
Cwe
November 4, 2016, 2:19pm
7
?=
is for positive look ahead
gri
November 4, 2016, 2:20pm
8
But from what I see, the 3rd capturing group starts with the parenthesis just after “(class=)([”’])"
Cwe
November 4, 2016, 2:24pm
9
Explanation from http://stackoverflow.com/questions/171480/regex-grabbing-values-between-quotation-marks
Just keep in mind I have added another capture. (So \1 becomes \2, \2 becomes \3.)
([""']) match a quote; ((?=(\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.
Cwe
November 4, 2016, 2:26pm
10
I could probably remove that gooble, since I’m not expecting backslashes in class names.
I’m guessing backslash in class names is invalid anyway.
Cwe
November 4, 2016, 2:27pm
11
Issue still remains though, that it works in the browser console and not in Enonic XP. For all I know it might be a bug in Nashorn…
Cwe
November 4, 2016, 2:37pm
12
I don’t think this is important though. Very corner case.