0

真的,问题很简单,为什么这不起作用?以及如何以清白的方式实现我想要的?

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

1 回答 1

1

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

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

所以:

toClean.replace(/([&"'<>](?!quot;|lt;|gt;|apos;|amp;))/g, (match, sub1) => _.toUpper(sub1));
于 2019-07-19T18:55:11.223 回答