3

I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?

I have:

var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;

and want something like: var string_url = "http://www.example.com/?{a}blabla={b}" and then redirect somehow.

In PHP I would go with that code for example: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">

3 Answers 3

7

You can add strings in JavaScript, "a" + "b" == "ab" evaluates to true.

So what you want is probably var string_url = "http://www.example.com/?" + a + "&blabla=" + b;

But you should ever escape vars especially if they come from inputs, so try

a = encodeURIComponent(a);
b = encodeURIComponent(b);

And then

var string_url = "http://www.example.com/?" + a + "&blabla=" + b;

To redirect you can use window.location:

window.location = string_url;
Sign up to request clarification or add additional context in comments.

Comments

0

use the ampersand to split vars

var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b

Could be made more sopisticated, but that in essence is what you need

1 Comment

This is taking user input. The data needs escaping or it will break.
0

JavaScript doesn't do string interpolation. You have to concatenate the values.

var uri = "http://example.com/?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;

Comments

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.