Discuss Scratch

PullJosh
Scratcher
1000+ posts

Regular Expression Help?

I'm try to make something a bit like what Sparks did - an image api.
I have no idea why. I'm not going to use it for anything.
But I want to do it.

Anyway, I've got some code that doesn't seem to be working. Here's my code:
function GetUrlValue(VarSearch){
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
        if(KeyValuePair[0] == VarSearch){
            return KeyValuePair[1].replace(/+/g, " ");
        }
    }
}
This should, in theory, grab a “get” value from a URL. And it does. The problem, though, is this line:
return KeyValuePair[1].replace(/+/g, " ");
I'm trying to replace all the plus signs with spaces. The /+/g part is, apparently, according to random people, a regular expression. And it doesn't work. I can't use a normal string (“+”) because then (darn it) JS only replaces the first + sign. When I go into the console (Chrome Canary), all it says is this:
Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat

Can anybody help me replace all the + signs with spaces?

Last edited by PullJosh (June 24, 2014 13:58:35)

nXIII
Scratcher
1000+ posts

Regular Expression Help?

You need to escape the +. Use /\+/g.

nXIII · GitHub
scimonster
Scratcher
1000+ posts

Regular Expression Help?

nXIII wrote:

You need to escape the +. Use /\+/g.
That's because the + means ‘one or more of the preceding character’ IIRC.

Retired Community Moderator
BTW, i run Google Chrome 41.0.2272.101 on a Linux system - Ubuntu 14.04. NEW: iPad 4th gen. w/retina.

418 I'm a teapot (original - to be read by bored computer geeks)
THE GAME (you just lost)
; THE SEMICOLON LIVES ON IN OUR SIGS
PullJosh
Scratcher
1000+ posts

Regular Expression Help?

scimonster wrote:

nXIII wrote:

You need to escape the +. Use /\+/g.
That's because the + means ‘one or more of the preceding character’ IIRC.
Okay, thanks Sci and nXIII. It works perfectly now. I guess I'll request for this to be closed.
Paddle2See
Scratch Team
1000+ posts

Regular Expression Help?

Closed by request of the topic owner.

Scratch Team Member, kayak and pickleball enthusiast, cat caregiver.

This is my forum signature! On a forum post, it is okay for Scratchers to advertise in their forum signature. The signature is the stuff that shows up below the horizontal line on the post. It will show up on every post I make.
(credit to Za-Chary)



;

Powered by DjangoBB