JS字符串:用正则表达式中的索引替换 [英] JS string: Replace with index in regex

查看:146
本文介绍了JS字符串:用正则表达式中的索引替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对regex几乎没有经验,我想知道您将如何替换由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?

这是我的示例字符串:

let exampleStr = "How do I {0} the {n} with the {1} in my array?";

这是我的数据数组:

let arr = ["replace", "items"];

现在,使用replace和regex,我想将{#}部分中的索引与匹配索引的数组元素进行匹配.

Now, with replace and regex, I would like to match the index in the {#} section with the array element matching the index.

结果字符串:

let result = "How do I replace the {n} with the items in my array?";

请注意,由于它不包含数字值,它将如何忽略{n}.

Notice how it would ignore the {n}, as it does not contain a numeric value.

我可以使用Array.indexOf,Number.isNaN,typeof等来执行此操作,但是正则表达式似乎是正确"且更干净的方法,虽然有点难于阅读:)

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 :)

谢谢.

推荐答案

您可以使用

You can use replace with a callback:

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

模式很简单-它在花括号内匹配一个数字,并将该数字捕获为组编号1.
回调函数解析数字(这不是严格要求的,但是 arr ["1"] 并不漂亮),然后从数组中返回正确的元素.
回调可以使用更多错误检查.

The pattern is simple - it matches a number inside curly braces, and captures the number to group number 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.
The callback could use some more error checking.

这篇关于JS字符串:用正则表达式中的索引替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆