简体   繁体   中英

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?

any help would be great

You want to replace staffID use following regexp pattern,

Check this Demo jsFiddle

jQuery

str = "id=3&staffID=4&projectID=5";    
str = str.replace(/staffID=\d/g, "staffID=10");  
console.log(str);

Console Result

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 ,

jQuery

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);

Console Result

id=1&staffID=2&projectID=3 

Check this Demo Hope this help you!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM