用jQuery替换字符串中的数字 [英] Replacing a number in a string with jquery

查看:764
本文介绍了用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.

这篇关于用jQuery替换字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆