[英]JQuery: replace string with regex
i have a string like this: 我有一个像这样的字符串:
var stringA = "id=3&staffID=4&projectID=5";
how do i use regex to replace the value of staffID=4 to staffID=10? 如何使用正则表达式将staffID = 4的值替换为staffID = 10?
any help would be great 任何帮助都会很棒
You want to replace staffID use following regexp pattern, 您要按照正则表达式模式替换staffID使用,
str = "id=3&staffID=4&projectID=5";
str = str.replace(/staffID=\d/g, "staffID=10");
console.log(str);
id=3&staffID=10&projectID=5
Same way you can change id, staffID and projectID using /id=(\\d+)&staffID=(\\d+)+&projectID=(\\d+)/g,
REGEXP pattern , 您可以使用
/id=(\\d+)&staffID=(\\d+)+&projectID=(\\d+)/g,
REGEXP 模式更改ID,staffID和projectID的方法相同
str = "id=3&staffID=12&projectID=5";
str = str.replace(/id=(\d+)&staffID=(\d+)+&projectID=(\d+)/g, "id=1&staffID=2&projectID=3");
console.log(str);
id=1&staffID=2&projectID=3
Here is the simple regex you are looking for. 这是您要查找的简单正则表达式。
result = stringA.replace(/(id=\d+&staffID=)\d+(&projectID=\d+)/g, "$110$2");
Basically, the expression captures everything before the staffID into Group 1, and captures everything after the staffID into Group 2. 基本上,该表达式将职员ID之前的所有内容捕获到组1中,并将职员ID之后的所有内容捕获到组2中。
Then we replace the string with the Group 1 capture, concatenated with "10", concatenated with Group 2. That is the meaning of the "$110$2" replacement. 然后,将字符串替换为第1组捕获,并与“ 10”连接,并与第2组连接。这就是“ $ 110 $ 2”替换的含义。 The first number looks like 110, but the first 1 actually belongs to the $ ($1 means Group 1 in a replacement string).
第一个数字看起来像110,但第一个数字实际上属于$($ 1表示替换字符串中的组1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.