How to remove the characters from a certain point with Jquery?

2

How do I remove everything I have before ? in this string smartphones?marca=3 or celular?marca=4 displaying only what is after the " ? " question mark with Jquery or Javascript?

    
asked by anonymous 15.09.2015 / 19:54

2 answers

2

You can separate this string by the character you want and then use only the second part. For example:

var marca = 'smartphones?marca=3'.split('?')[1];
console.log(marca); // marca=3

But what you want is to transform a query string into an object to work right? In this case you can do this:

function converterQS(str) {
    var data = str.split('?')[1];
    var pares = data.split('&');
    var obj = {};
    pares.forEach(function (par) {
        var partes = par.split('=');
        obj[partes[0]] = partes[1];
    });
    return obj;
}

console.log(converterQS('smartphones?marca=3')); // Object {marca: "3"}

jsFiddle: link

    
15.09.2015 / 19:56
2

Solution with regex:

"smartphones?marca=3".replace(/.+\?/g, "");

Fiddle

    
15.09.2015 / 20:01