简体   繁体   中英

JavaScript string replace with replacement coming from the return of lodash function having param as regex capture group

Really the question is simple why this won't work? And how do I achieve what i want in a clean conscience manner?

var toClean = "Test & &";
var result = toClean.replace(/([&"'<>](?!quot;|lt;|gt;|apos;|amp;))/g,_.escape("$1"));
console.log(result); // prints => "Test &amp; &" 
// what i expect is => "Test &amp; &amp;"

Keeping in mind that this works:

var toClean = "Test &amp; &";
var result = toClean.replace(/([&"'<>](?!quot;|lt;|gt;|apos;|amp;))/g,
_.toUpper("a"));
console.log(result); // prints => "Test &amp; A"

The $1 backreference will only work directly in the replace function, not in parameters passed to other functions. Luckily, String.replace can use a function as a replacement instead of just a string; in that case, the matched substrings are passed to the callback as parameters, and then whatever the function returns will be used as a replacement.

For a global replacement, the callback is called once for each match. The first argument is the full match, the second is the first captured group, the third is the second captured group, etc.

So:

toClean.replace(/([&"'<>](?!quot;|lt;|gt;|apos;|amp;))/g, (match, sub1) => _.toUpper(sub1));

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