用jQuery替换字符串中的数字

用jQuery替换字符串中的数字

问题描述:

我有一个字符串,其中包含一个数字,我想用另一个数字替换.

I have a string which has a number in it that I would like to replace with another number.

<a href="" id="my_link">blah blah 32 blah blah</a>

我知道此字符串中只会有1个数字.

I know there is only going to be 1 number in this string.

我可以做到这一点:

var my_string = $('a#my_link').text();

但是基本上我不知道如何在my_string上搜索数字并将其替换为其他数字.

But basically I don't know how to then perform a search on my_string for a numeral and replace that number with something else.

使用jQuery是否可能?

Is that possible with jQuery?

感谢任何想法.

许多jQuery方法,例如.text()都可以接受一个返回要插入值的函数.

Many jQuery methods like .text() can accept a function that returns the value to insert.

尝试一下: http://jsfiddle.net/6mBeQ/

$('#my_link').text( function(i,txt) {return txt.replace(/\d+/,'other value'); });

这消除了运行选择器两次的需要.

This removes the need to run the selector twice.

此外,当您通过元素的ID获取元素时,如果不包含标签名称,则实际上要快一些.

Also, when you are getting an element by its ID, it is actually a little quicker if you do not include the tag name.

所以不是

$('a#my_link')

最好做

$('#my_link')

就像我上面所做的那样.

as I did above.