简体   繁体   中英

Replace regex with same number of chars

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM