繁体   English   中英

JavaScript字符串替换为来自具有参数作为正则表达式捕获组的lodash函数的返回的替换

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

真的问题很简单,为什么这不起作用? 我如何以一种良知的方式实现我想要的?

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;"

请记住,这有效:

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

$ 1反向引用只能直接在replace函数中使用,而不能在传递给其他函数的参数中使用。 幸运的是, String.replace可以使用函数代替字符串,而不仅仅是字符串。 在这种情况下,匹配的子字符串将作为参数传递给回调,然后该函数返回的任何内容都将用作替换。

对于全局替换,对于每个匹配,都将调用一次回调。 第一个参数是完全匹配,第二个参数是第一个捕获的组,第三个参数是第二个捕获的组,依此类推。

所以:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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