开发者

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/mainpa开发者_StackOverflowge.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"

Thanks!!


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


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.


string.replace( /pattern/, replace_text );

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

or

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜