首页 > 解决方案 > 如何获取字符串中双下划线之间的数字并将其与另一个数字相乘?

问题描述

假设我有一个示例字符串,

let str = "Congrats! ID: 342, your salary is increased by __5%__ and it will increase by __10%__ next month.";

我需要得到双下划线之间的数字(例如:__5%__ 和 __10%__,如上所示)并将它们乘以 2。所以我的输出应该是,

let result = "Congrats! ID: 342, your salary is increased by __10%__ and it will increase by __20%__ next month.";

注意:数字 342 应该保持不变,因为它不在双下划线之间。

我怎样才能得到这个?提前致谢。

标签: javascriptdiscord.js

解决方案


您可以使用String.replace()这样的回调函数:

let str = "Congrats! ID: 342, your salary is increased by __5%__ and it will increase by __10%__ next month.";

let res=str.replace(/__(\d+)%__/g,function(_,num){return "__"+(2*num)+"%__"});
console.log(res)


推荐阅读