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 ?

1
  • Basic string concatenation. window.open('http://example.com/?q='+ myname); Commented Oct 30, 2019 at 20:57

3 Answers 3

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

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

1 Comment

Thx everybody for hint, I've sorted many similar variations but not literal ! Solved and work with Microsoft Edge, at-least...
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 

2 Comments

Thx for hint, I've sorted many similar variations but not literal ! Solved !
You were first :)
1

You have to wrap the URL in Template Literals

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

3 Comments

You don't "have to". You can use simple concatenation.
Well "have to" should be "Should have to". The cleanest way of doing concatenation is the Template Literals
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.