2

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?

1
  • your required string has changed the & to & is it how you want it? I assumed it was a typo error. Commented Nov 3, 2016 at 7:43

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

I would use a split on &. So you get a array with all (but one) options. Then you take the first element of the array and split it at ?. You can look at each option if it is needed and remove or let it inside the array. Then you can add you own options. If everything is ok you can join it and have you url.

(http://www.w3schools.com/jsref/jsref_split.asp)

(http://www.w3schools.com/jsref/jsref_join.asp)

Other approach is a replace with regex. (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

Comments

0

Your can use the URL api to achieve this:

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

var url = new URL(str);
var urlParams = url.searchParams;

// add or replace certain keys
urlParams.set('layout', 'download');
urlParams.set('fileid', yourFileId);
urlParams.delete('id');

// the final url
var result = url.toString();

But, since this is still rather experimental (especially URLSearchParams) consider using a polyfill.

Comments

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.