Скажем, у меня есть пример строки,
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 должно остаться прежним, так как оно не находится между двойным подчеркиванием.
Как я могу получить это? Заранее спасибо.
Вы можете использовать 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.info(res)
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%"
Любая попытка кода?