Javascript RegExp: replace parameter value in query string

Task: change the value of parameter 'tid' in given querystring.
Original querystring:

var linkParam = 'tid=8&id=11008&location=news';

New 'tid' parameter value:

var tagId = 12;

You can do it using 'replace' function. Final code to replace:

var tagIdReg = /[tid=](\d+)[&]/i;
document.write(linkParam.replace(tagIdReg, '='+tagId+'&'));


But if you need just extract 'tid' value use 'exec':

var tagIdReg = /[tid=](\d+)[&]/i;
var regResult = tagIdReg.exec(linkParam);
document.write(regResult[1]);

Comments

Popular posts from this blog

Using Trello and Confluence to manage UX design project. Part 2

How do I use InVision

Using Trello and Confluence to manage UX design project. Part 1