0

First of all - this question has no answers at Include variable in URL or How can I do string interpolation in JavaScript? I tested many variants from elsewhere before my question here. For example, as advised at Include variable in URL

window.open('http://example.com/?q="+ myname"');

does not work with the script below. A kind of specific wrapping is needed.

So, simplest script

<script type="text/javascript">
function sendquery() {
var myname = "John";
alert(myname);
window.open('http://example.com/?q=(myname)');
}
</script>
<button onclick="sendquery()">Query</button>

Alert perfectly shows variable John. But query sends not variable John but (myname).

Or + myname - if follow other answers.

How to wrap variable to URL query ?

Serge
  • 679
  • 1
  • 9
  • 23

3 Answers3

2

It looks like you're just putting the variable in the string incorrectly. Check out template literals if you don't need to support IE.


var myname = "John";
// won't work
window.open('http://example.com/?q="+ myname"');
// will produce 'http://example.com/?q=John'
window.open(`http://example.com/?q=${myname}`);

and likewise

// won't work
window.open('http://example.com/?q=(myname)');
// valid
window.open(`http://example.com/?q=${myname}`);

If you do need to support IE then window.open('http://example.com/?q=' + myname); should work

Josh G
  • 644
  • 7
  • 21
  • Thx everybody for hint, I've sorted many similar variations but not literal ! Solved and work with Microsoft Edge, at-least... – Serge Oct 30 '19 at 21:01
1

Your string concatenation is not correct

var myname = "test"
window.open("http://example.com/?q=" + myname); // Classic string concatenation
window.open(`http://example.com/?q=${myname}`); // Using template literal 
Mike Ezzati
  • 2,968
  • 1
  • 23
  • 34
1

You have to wrap the URL in Template Literals

window.open(`http://example.com/?q=${myname}`);
Anand G
  • 3,130
  • 1
  • 22
  • 28
  • You don't "have to". You can use simple concatenation. – Scott Marcus Oct 30 '19 at 20:56
  • Well "have to" should be "Should have to". The cleanest way of doing concatenation is the Template Literals – Anand G Oct 30 '19 at 21:00
  • That's an opinion. I think `a + "test"` is cleaner than a${test} (<-- not sure how to put back-tick in an SO comment so that it actually appears as opposed to formats the contents as code). – Scott Marcus Oct 30 '19 at 21:02