Reputation: 1244
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?
any help would be great
Upvotes: 2
Views: 2340
Reputation: 27614
You want to replace staffID use following regexp pattern,
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,
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
Check this Demo Hope this help you!
Upvotes: 3
Reputation: 41838
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.
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. The first number looks like 110, but the first 1 actually belongs to the $ ($1 means Group 1 in a replacement string).
Upvotes: 1