user815460
user815460

Reputation: 1143

javascript regex to replace a substring

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!!

Upvotes: 0

Views: 746

Answers (3)

Artem O.
Artem O.

Reputation: 3487

string.replace( /pattern/, replace_text );

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

or

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

Upvotes: 0

rapidfyre
rapidfyre

Reputation: 65

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.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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

Upvotes: 2

Related Questions