0

I need to replace the content found used a regex with the same number of characters using a character defined by me.

For example:

content: "abcdefghi*!?\"asd";

should becomes:

content: "-----------------";

This is my regexp:

new RegExp("('|\").*('|\")", "gm")

And this is my attempt took from this answer (Javascript Regex- replace sequence of characters with same number of another character):

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0, $1, $2, $3) {
            return $1 + (new Array($2.length + 1).join("-")) + $3;
        });

But it doesn't work.

Using it on this input:

::selected {
    color: purple
}
a {
    color: purple
}
a:hover {
    color: purple
}
a {
    color: purple
}
a:not("foobar\";{}omg") {
    content: 'example\';{} text';
    content: "example\";}{ text"
}
a {
    color: purple
}

I get this output:

::selected {
    color: purple
}
a {
    color: purple
}
a:hover {
    color: purple
}
a {
    color: purple
}
a:not("-117) {
    content: '-150;
    content: "-184
}
a {
    color: purple
} 

If I use the regexp replacing the content with null it works fine, so is not a problem of regex.

Any help?

Community
  • 1
  • 1
Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160
  • Related/dupe for pure regex: http://stackoverflow.com/questions/7337995/regex-replace-sequence-of-one-character-with-same-number-of-another-character – blahdiblah Apr 27 '17 at 20:01

2 Answers2

0

The replacement function requires three (catching) groups to be present in the regular expression but there are only two of them. Therefore the $3 gets the offset of the match which is the unexpected number you get. For details see Specifying a funciton as a parameter in Mozilla JS reference.

Use something like "('|\")(.*)('|\")" (3 groups) for your regular expression.

halfbit
  • 3,414
  • 1
  • 20
  • 26
0

Ok seems I've solved it...

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0) {
    return (new Array($0.length + 1).join("-"));
});

Thanks for all the answers however.

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160