0

In javascript, how would I use a regular expression to replace everything to the right of "Source="

Assume, for example:

var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"

Goal is to get this value in outStr:

var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"

Thanks!!

3 Answers 3

2

Assumes that source= will always be at the end

var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, works perfectly, if you have the time, I'd be grateful if you could briefly explain how it works. Thanks for the solution.
Basic regular expression. The () is a capture group so it remembers what it matches. It is read with $1 since it is the first capture group. . means any character and * says to match one or more times.
So, the replace method has 2 parameters, and the text that matches the pattern in the first parameter will be replaced with the resolved value of the second parameter. The () does not affect the pattern matching, it just remembers what it matches for later use with the $1.
correct Documentation on replace() and reg exp
0

Is "Source" always linked to the first occurrance of "&"? You could use

indexOf("&") + 7

(number of letters in the word "Source" + one for "=").

Then create the new string by appending the new source to the substring using the index from before.

Comments

0

string.replace( /pattern/, replace_text );

var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );

or

var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

2 Comments

Why the capture group around the part you are throwing away?
Oh, sure. Capture group for right text after the &Source= doesn't needed

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.