Avatar of Jonathan Greenberg
Jonathan Greenberg
Flag for United States of America asked on

JavaScript string variable problem

I'm trying to use a string from a JavaScript variable in a window.open function. My function looks like this:

<script type="text/javascript">
function url1() {
    var linkstr1 = "'http://google.com'";
    window.open(linkstr1);
}
</script>

But when I call this function from an a href, the resulting url is:

http://www.mysite.com/directory/'http://google.com'

How do I properly use a variable as a window.open url? Thanks.
JavaScript

Avatar of undefined
Last Comment
leakim971

8/22/2022 - Mon
leakim971

you don't need the quotes inside :

function url1() {
    var linkstr1 = 'http://google.com';
    window.open(linkstr1);
}

Open in new window

leakim971

or you may use : http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

<script type="text/javascript">
function url1() {
    var linkstr1 = "http://google.com";
    window.open(encodeURIComponent(linkstr1));
}
</script>

Open in new window

Jonathan Greenberg

ASKER
Thanks, leakim. My real goal is to get the following string in the window.open:

"http://google.com","_self"

Open in new window

To do that, my function now looks like this:

function url1() {
    var linkstr1 = "'http://google.com','_self'";
    window.open(linkstr1);
}

Open in new window

But that results in this url:

http://www.mysite.com/directory/'http://google.com','_self'

Open in new window

How can I use a variable for that string?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
leakim971

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Jonathan Greenberg

ASKER
That works! Thanks so much, leakim.
leakim971

you're welcome!