Adding a variable in the middle of the link in javascript

时间:2015-07-28 15:54:20

标签: javascript

I am new to javascript. I am trying to append a variable to a link like this. I am able to get the var name but it's not working when I append. i tried couple of other things. Any suggestions for appending the variable name.

  <script type="text/javascript">
  var name = document.getElementById('name').value;
  window.location.href = "http://example.com?id=5678&name=+name+&code=1234
  </script>

2 个答案:

答案 0 :(得分:0)

Simply end and restart the quotes like so

window.location.href = "http://example.com?id=5678&name="+name+"&code=1234";

答案 1 :(得分:0)

You can imitate sprintf function by:

window.location.href = 
    "http://example.com?id=5678&name=%name&code=%code"
    .replace('%name', 'myName')
    .replace('%code', '123456');
相关问题