3 回答

TA貢獻1813條經驗 獲得超2個贊
您可以使用String.replace()這樣的回調函數(shù):
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是否以“%”結尾,如果是,則乘以兩次即可。
并以相同的模式再次加入數(shù)組。
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%"
添加回答
舉報