Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取字符串中双下划线之间的数字并将其与另一个数字相乘?_Javascript_Discord.js - Fatal编程技术网

Javascript 如何获取字符串中双下划线之间的数字并将其与另一个数字相乘?

Javascript 如何获取字符串中双下划线之间的数字并将其与另一个数字相乘?,javascript,discord.js,Javascript,Discord.js,假设我有一个示例字符串 let str=“恭喜!ID:342,您的工资增加了5%,下个月将增加10%。”; 我需要得到双下划线之间的数字(如上图所示:_5%_和_10%_),然后将它们乘以2。 所以我的输出应该是 let result=“恭喜!ID:342,您的工资增加了10%,下个月将增加20%。”; 注意:数字342应该保持不变,因为它不在双下划线之间 我怎么能得到这个?提前感谢。您可以使用如下回调函数使用String.replace(): let str=“恭喜!ID:342,您的工

假设我有一个示例字符串

let str=“恭喜!ID:342,您的工资增加了5%,下个月将增加10%。”;
我需要得到双下划线之间的数字(如上图所示:_5%_和_10%_),然后将它们乘以2。 所以我的输出应该是

let result=“恭喜!ID:342,您的工资增加了10%,下个月将增加20%。”;
注意:数字342应该保持不变,因为它不在双下划线之间


我怎么能得到这个?提前感谢。

您可以使用如下回调函数使用
String.replace()

let str=“恭喜!ID:342,您的工资增加了5%,下个月将增加10%。”;
让res=str.replace(/_uud+)%_g/g,函数(u,num){return“_uu+(2*num)+”%uuu});
console.log(res)
  • 您可以按模式“\uuuu”拆分str
  • 检查str是否以“%”结尾,如果以“%”结尾,只需将其乘以两次即可
  • 并以相同的模式再次加入阵列

有代码尝试吗?
  str
  .split("__")
  .map(maybeNumber => {
    if (maybeNumber.endsWith("%")) {
      return `${parseInt(maybeNumber) * 2}%`
    }

    return maybeNumber;
  })
  .join("__")
var str = "Congrats! ID: 342, your salary is increased by __5%__ and it will increase by __10%__ next month.";

var idInString = str.match(/\d+/)[0];
str = str.replace(idInString,""); // result is "Congrats! ID: , your salary is increased by __5%__ and it will increase by __10%__ next month." Now, with the first number at the beginning of string. Now, we can use the same method to get the other two numbers.

var firstNumberInString = str.match(/\d+/)[0];
document.write(firstNumberInString*2+"%"); // results in "10%"

str = str.replace(firstNumberInString,""); 

var secondNumberInString = str.match(/\d+/)[0];
document.write(secondNumberInString*2+"%"); // results in "20%"