您可以使用Jquery操纵字符串中的数字吗? [英] Can you manipulate a number within a string with Jquery?
本文介绍了您可以使用Jquery操纵字符串中的数字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些像这样的字符串:
I have some strings like so:
<p>It will vary from 100g to 200g</p>
<p>2lbs of meat</p>
<p>3 piles of timber</p>
等等等
我想增加/减少每个字符串中的所有数字. 有指针吗?
I would like to increment/decrement all numbers in each string. Any pointers?
附加说明:
- 否,数字可以在字符串中的任何位置.
- @cookie_monster我想看看没有常规操作是否有可能.
推荐答案
A simple solution would be to use a regular expression, for example:
"100g".replace(/\d+/g, function(n) { return +n + 1; }); // 101g
说明:
- 模式
\d+
匹配字符串中一个或多个数字的任何序列.- 此模式仅将您限制为整数;如果您尝试使用
"3.5"
进行操作,它将被认为是两个单独的整数,结果将是"4.6"
. - 如果这是一个问题,请改用
(\d+\.)?\d+
这样的模式.
- The pattern
\d+
matches any sequence of one or more digits in a string.- This pattern limits you to integers only; if you tried this with
"3.5"
it would consider this to be two separate integers and the result would be"4.6"
. - If this is a problem, use a pattern like
(\d+\.)?\d+
instead.
- 如果只想替换第一个实例,请删除它.
要使用jQuery在HTML元素中执行此操作,您可以简单地使用以下内容:
To do this within an HTML element using jQuery, you could simply use something like this:
$('p').each(function() { var e = $(this); e.text(e.text().replace(/\d+/g, function(n) { return +n + 1; })); });
这篇关于您可以使用Jquery操纵字符串中的数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- This pattern limits you to integers only; if you tried this with
- 此模式仅将您限制为整数;如果您尝试使用
查看全文