[英]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 & &"
// what i expect is => "Test & &"
Keeping in mind that this works: 请记住,这有效:
var toClean = "Test & &";
var result = toClean.replace(/([&"'<>](?!quot;|lt;|gt;|apos;|amp;))/g,
_.toUpper("a"));
console.log(result); // prints => "Test & A"
The $1 backreference will only work directly in the replace function, not in parameters passed to other functions. $ 1反向引用只能直接在replace函数中使用,而不能在传递给其他函数的参数中使用。 Luckily,
String.replace
can use a function as a replacement instead of just a string; 幸运的是,
String.replace
可以使用函数代替字符串,而不仅仅是字符串。 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.