3 回答
TA贡献1813条经验 获得超2个赞
您可以使用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)
TA贡献1824条经验 获得超5个赞
您可以按模式“__”拆分 str。
检查str是否以“%”结尾,如果是,则乘以两次即可。
并以相同的模式再次加入数组。
str
.split("__")
.map(maybeNumber => {
if (maybeNumber.endsWith("%")) {
return `${parseInt(maybeNumber) * 2}%`
}
return maybeNumber;
})
.join("__")
TA贡献1804条经验 获得超3个赞
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%"
添加回答
举报