简体   繁体   English

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

[英]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. $ 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.

相关问题 这个捕获组在 Javascript 的替换函数文档中的这个正则表达式中做了什么? - What is this capture group doing in this regex expression in the replace function documentation in Javascript? 在 Javascript 中用大写替换正则表达式捕获组 - Replace a Regex capture group with uppercase in Javascript Javascript正则表达式返回捕获组值 - Javascript regex return capture group value 正则表达式解释和javascript的替换功能。 我们为什么需要捕获小组? - Regex interpretation and javascript's replace function. Why do we need the capture group? javascript - 字符串替换,将“^”替换为“”,将“^^”替换为“^” - javascript - string replacement, replace “^” with “” and “^^” with “^” 正则表达式对字符串中的递归模式进行分组并将捕获组作为数组返回 - Regex to group recursive pattern in string and return capture group as array JavaScript Regex捕获和替换 - JavaScript Regex capture and replace 字符串替换正则表达式匹配的捕获组,除非不同的正则表达式匹配 JS 中的相同捕获组 - String replace regex match's capture group unless a different regex matches the same capture group in JS 使用Javascript或Lodash替换字符串 - Use Javascript or Lodash to replace string Javascript-正则表达式。 替换字符串中的所有空格,但是从函数中调用 - Javascript - Regex. Replace all spaces in a string, but called from a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM