Keren Keren - 1 month ago 7
jQuery Question

How to insert and modify string in jquery?

This is the string received:

http://mysite.localhost.com/index.php?option=com_social&view=conversations&id=&Itemid=127


I need to change it into this:

index.php?option=com_social&view=conversations&layout=download&fileid=279&Itemid=127


things need to change:

1) add layout=download&fileid=VALUE IN VARIABLE&

2) id change to fileid

I've tried using
url.substr(0, url.indexOf('conversations&'))
to teh first string before the specific string.

Then manually added,

permanentlink = url.substr(0, url.indexOf('conversations&'));
permanentlink+'conversations&layout=download&fileid='+id+'&Itemid=127'


But this keeps concatnating the string.. And I'm not sure the correct way of doing this.Can someone help?

Answer

Try replacing it using regex :

var url = 'http://mysite.localhost.com/index.php?option=com_social&view=conversations&id=&Itemid=127' + '&layout=download';
var newValue = 12222;
var newStr = url.replace(/id=/, 'fileid=' + newValue );
// remove this if doesnt want to replace &
var againNewStr = newStr.replace(/&/g, '&');
alert(againNewStr);