use*_*333 -3 javascript jquery
如果你有:
var something = $('.element').text();
// something = 'The tortoise ran 5 times faster than the fox.';
Run Code Online (Sandbox Code Playgroud)
有没有办法可以编辑它以将"5"更改为新var中的不同数字?所以我明白了
newSomething = 'The tortoise ran 6 times faster than the fox.';
Run Code Online (Sandbox Code Playgroud)
注意:var中的数字是动态的,是0 - > 100的任何数字,我需要将它递增1,我需要动态增加它(我不能将数字分配给var,因为它来自文档加载正在分配)
var something = $('.element').text();
var newSomething = something.replace(/\d+/, function(match) {
return (Number(match) + 1).toString();
});
Run Code Online (Sandbox Code Playgroud)
有关正在发生的事情的一些信息:代码使用更复杂的str.replace函数形式.普通形式只需要两个字符串,并用第二个字符串替换第一个字符串的任何出现.
str.replace也可以使用正则表达式来搜索(在这种情况下,\d+这意味着"一个或多个数字"),以及我在这里使用的替换函数.我使用了一个匿名函数表达式,它只接受一个参数match.每个匹配都会调用此函数,因此如果您的字符串有多个匹配项,那么它将被多次运行.
在函数中,匹配(字符串)将被转换为数字,递增,然后转换回字符串.然后作为匹配替换器的结果返回.