Serge
Serge

Reputation: 741

Javascript how to pass variable to URL query with window.open

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 ?

Upvotes: 0

Views: 1350

Answers (3)

Mike Ezzati
Mike Ezzati

Reputation: 3166

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 

Upvotes: 1

Josh G
Josh G

Reputation: 644

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

Upvotes: 2

Anand G
Anand G

Reputation: 3200

You have to wrap the URL in Template Literals

window.open(`http://example.com/?q=${myname}`);

Upvotes: 1

Related Questions