[英]JS string: Replace with index in regex
I have little to no experience with regex, and I was wondering how you would go about to replace a section in a string identified by regex, where the index is part of the identified section? 我几乎没有使用regex的经验,我想知道您将如何替换由regex标识的字符串中的某个部分,其中索引是所标识部分的一部分?
Here is my example string: 这是我的示例字符串:
let exampleStr = "How do I {0} the {n} with the {1} in my array?";
This is my data array: 这是我的数据数组:
let arr = ["replace", "items"];
Now, with replace and regex, I would like to match the index in the {#} section with the array element matching the index. 现在,使用replace和regex,我想将{#}部分中的索引与匹配索引的数组元素进行匹配。
Resulting string: 结果字符串:
let result = "How do I replace the {n} with the items in my array?";
Notice how it would ignore the {n}, as it does not contain a numeric value. 请注意,由于它不包含数字值,它将如何忽略{n}。
I can do this with Array.indexOf, Number.isNaN, typeof etc, but regex seems to be the "right" and cleaner way to do it, while a bit harder to read :) 我可以使用Array.indexOf,Number.isNaN,typeof等来做到这一点,但是正则表达式似乎是“正确”且更清洁的方式,虽然有点难于阅读:)
Thanks in advance. 提前致谢。
You can use replace
with a callback : 您可以使用带有回调的replace
:
let exampleStr = "How do I {0} the {n} with the {1} in my array?"; let arr = ["replace", "items"]; let result = exampleStr.replace(/\\{(\\d+)\\}/g, (g0, g1)=>arr[parseInt(g1,10)]); console.log(result);
The pattern is simple - it matches a number inside curly braces, and captures the number to group number 1. 模式很简单-它匹配花括号内的数字,并将该数字捕获为组号1。
The callback function parses the number (which is not strictly required, but arr["1"]
is not pretty), and then return the proper element from the array. 回调函数解析数字(这不是严格要求的,但是arr["1"]
并不漂亮),然后从数组中返回正确的元素。
The callback could use some more error checking. 回调可以使用更多的错误检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.