How to remove characters from a certain point with Jquery?

Asked

Viewed 4,643 times

2

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

2 answers

3

Solution with regex:

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

Fiddle

  • Using Regex to interpret text patterns is the best option.

  • @Davidschrammel also prefer.

  • I can only take what’s before the ? also?!

  • @wDrik.. .+(?=\?)

  • @Dontvotemedown didn’t work "smartphones?marca=3".replace(/.+(?=\?)/g, ""); so he returns ?marca=3 need the smartphones

  • @wDrik use match() or remove what comes after interrogation \?.+

  • \?.+ Cool worked. however the element I need is to remove exactly one . and it didn’t go very well.. for example I have photo.jgp wish to remove the .jpg and keep only photo Note: has to be via REGEX!

  • 1

    @wDrik \..+..

Show 3 more comments

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 turn one query string on an object to be able to work right? In that case you can do so:

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: http://jsfiddle.net/ejovrdg8/1/

  • In what situation the split() can return a string?

  • @Dontvotemedown the split generates a array and then you use [1] to take out the second element. Take a look at the example above in the answer.

  • I did, I just didn’t understand why this part: if (typeof pares == 'string') pares = [pares];. That’s why I asked. Because I think the split result will always be an array, wanted to know in which situation it returns a variable of type string.

  • @Dontvotemedown ah, you’re right. As I did the code at the time I didn’t notice that line any more than I would actually ever run :) Thank you! I fixed and removed that line.

  • Okay buddy. np =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.