Ricardo
Ricardo

Reputation: 708

jquery split string not working properly

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?

Upvotes: 0

Views: 731

Answers (1)

void
void

Reputation: 36703

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.

Upvotes: 3

Related Questions