0

I'm using Javascript to send variables through a websites url and am trying to prevent the variables being copied over and over when a user keeps changing the same field:

ie Admin.php?pid=2&ENT=New_Web_Site_Launched&ENA=Stuart&ENA=Stuart&ENA=Stuart

I have multiple fields and have managed to get the first part working by removing the first "&" and everything after it out of the url by using the following piece of code.

function reload(form)
{
var val=form.NewsTitle.options[form.NewsTitle.options.selectedIndex].value;
url = location.href;
url = url.replace(/&.*$/,"");
self.location= url + '&ENT=' + val;
}

But I am having trouble removing everything from the second "&" and everything after it as I can't figure out the regex for it.

function reload2(form)
{
var
val2=form.NewsAuthor.options[form.NewsAuthor.options.selectedIndex].value;
url = location.href;
url = url.replace(Regex Here);
self.location= url + '&ENA=' + val2;
}

If somebody could help me I need a regex that will grab everything after and including the second "&" and everything after it as follows:

ie Admin.php?pid=2&ENT=New_Web_Site_Launched&ENA=Stuart&ENA=Stuart&ENA=Stuart

thanks Callum

2 Answers 2

1
var url = "Admin.phppid=2&ENT=New_Web_Site_Launched&ENA=Stuart&ENA=Stuart&ENA=Stuart";
var regexp = /^([^&]*&[^&]*)&.*$/;
alert(url.replace(regexp, "$1"));

It will only give you Admin.php?pid=2&ENT=New_Web_Site_Launched but I'm not quite sure if you want to keep the first part (everything before the second &) or the second part.

Try it out: JSFiddle

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

1 Comment

Thanks guys for your respective answers. I got the answer above to work for me. cheers Callum
0

In java Use pattern and matcher to extract whatever there from second &

Pattern p = Pattern.compile("&.*(&.*)");
Matcher m = p.matcher("Admin.php?pid=2&ENT=New_Web_Site_Launched&ENA=Stuart&ENA=Stuart&ENA=Stuart");

if (m.find()) {
    url = url.replace(m.group(1),"");
}
System.out.println(url);

first of all it will match everything after second & from url,and then it will just replace it from your url

output : Admin.php?pid=2&ENT=New_Web_Site_Launched

In javascript

var url = "Admin.php?pid=2&ENT=New_Web_Site_Launched&ENA=Stuart&ENA=Stuart&ENA=Stuart"

var re = /&.*(&.*)/;
var result = re.exec(url);
if(result !=null)
{
   url = url.replace(RegExp.$1,"");
   alert(url);
}

2 Comments

That seems like Java to me.
It still doesn't work: http://jsfiddle.net/69f504q1/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.