2

My html:

<select onchange="getval(this);"> <option value="user1">user1</option> <option value="user2">user2</option> <option value="user3">user3</option> </select> <a class="local" href="http://subDomain.www.mysite.com">Site</a> <a class="local" href="http://subDomain.www.mysite.com/admin">Admin</a> <a class="local" href="javascript:open_wins('http://subDomain.mysite.com', 'http://subDomain.mysite.com/admin');">Both</a> 

My script:

<script> function getval(sel) { $(document).ready(function() { var x = (sel.value); var regex = new RegExp(Globally replace the subdomain of urls on select change); $('.local').attr('href', function(i, val) { return val.replace(regex, x); }); }); } </script> 

I want to be able to dynamically replace whatever the current subDomain string is, e.g., user1 with the option value I select from my form.

This script may not be elegant, but it works to replace a static string in the url. What I'm trying to do is replace everything between "http://" and ".", but try as I may, I cannot figure out the proper regex to do so.

5
  • You shouldn't have a $(document).ready within your getval function. It should be wrapping it if anything. Commented Jun 25, 2013 at 23:30
  • You mean http://subDomain.mysite.com should become http://user1.mysite.com? Commented Jun 25, 2013 at 23:30
  • mvChr: you are correct, and I can fix that. Commented Jun 25, 2013 at 23:33
  • hjpotter: Yes. And when I select user2 from my select box, user1 needs to become user2, etc. Commented Jun 25, 2013 at 23:33
  • Explosion Pills: That almost works, but it leaves off the last ".", e.g., subDomain.www.mysite.com becomes user1www.mysite.com. Commented Jun 25, 2013 at 23:39

1 Answer 1

2
function getval(sel) { var x = (sel.value); var regex = new RegExp(/http:\/\/\w+\./g); $('.local').attr('href', function (i, val) { return val.replace(regex, "http://" + x + '.'); }); } 

Here is a working fiddle: http://jsfiddle.net/3jbfD/

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

1 Comment

Thanks to everybody for smart, speedy responses! hjpotter92's solution works perfectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.