0

I'm trying to get some values from the url in the page. I'm not getting an array but a comma separated string. It works on the console but not on the site.

this is the url:

mysite.com/index.html?tags=tag2+tag1

This is my html header:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.parsecdn.com/js/parse-latest.js"></script>
    <script type="text/javascript" src="home_recipes_js.php"></script>

This is the js code:

checkDocumentReady();

function checkDocumentReady() {

    $(document).ready(function() {

        var tagsString = getUrlVars()["tags"];

        tagsParser(tagsString);
    });
}

function getUrlVars() {

    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function tagsParser(tagsString) {

    var rawTags = tagsString.split('+');

    console.log('rawTags : ' + rawTags.length + ' ' + rawTags);
}

this is the console output:

tagsString: 2 tag2,tag1

What I'm I doing wrong?

1
  • Nothing is wrong. See anwser below. If you want to output individual items in the array use indexes: rawTags[0] will give you first value in the array. Commented Jan 6, 2016 at 21:40

1 Answer 1

3

Try this

console.log(rawTags);

You will get an array.

When JavaScript concatenates an array to a string, it actually calls .join(',') on the array, so in your code

console.log('rawTags : ' + rawTags.length + ' ' + rawTags);

the interpreter translates it into

console.log('rawTags : ' + rawTags.length + ' ' + rawTags.join(','));

that is why you are getting a string at the end. Otherwise your code is fine.

Even then you want to see it as an array in the same way use JSON.stringify() on the array, like:

console.log('rawTags : ' + rawTags.length + ' ' + JSON.stingify(rawTags));

it will keep the bracket notation but it won't be an array literally.

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

1 Comment

It works, I was expecting to see the array in the log string :) Thanks! This was driving me crazy

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.