我有以下字符串:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|4093F6|FFFFFF
我想找到 chld=1
。
1
可以是任何数字,我需要更改它。
如何找到 chld=x
,其中 x
代表任意数字?
最佳答案
这里有一个可能的方法:
var re = /chld=\d+/;
var str = '"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|4093F6|FFFFFF"';
document.getElementById("res").innerHTML = str.replace(re, "chld=100");
<div id="res"/>
正则表达式是chld=\d+
,这是非常基础的:
chld=
- 匹配文字chld=
字符串\d+
- 匹配 1 个或多个数字。
如果你有多个 chld
,并且你想为它们设置相同的值,只需将 g
标志添加到 var re =/chld=\d+/g;
。作为使用 \d
的替代方法,您可以使用 [0-9]
字符范围实现相同的效果:var re =/chld=[0-9]+/g;
。但是,在 JavaScript 中,\d
和 [0-9]
are equal :
Since certain character classes are used often, a series of shorthand character classes are available.
\d
is short for[0-9]
. In most flavors that support Unicode,\d
includes all digits from all scripts. Notable exceptions are Java, JavaScript, and PCRE. These Unicode flavors match only ASCII digits with\d
.
关于javascript - 在字符串中查找部分匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30400289/