2

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

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Welcome i add more answer details
@user1153551 Your reply answers "how do I relace staffID=4 with staffID=10. This is not what David asked. There was some context around staffID, and given the question it should be assumed that he only wants to replace the staffID number when it appears in strings formed like "id=3&staffID=4&projectID=5"
that is what i want, i just need to replace the staffID, i dont care what is string infront or behind
1

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

1 Comment

@David You are welcome, just trying to answer according to the exact specs you gave us. :) Often, an imprecise regex will replace lots of strings that you don't want to replace. The devil is in the details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.