1

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :

  1. take url and check if it has a '?' followed by number with varying amount of digits.
  2. if the match is correct, get the number after the '?' sign
  3. exchange this number with different one.

So let's say we have this url :

http://website.com/avatars/avatar.png?56

we take '56' and change it to '57'.

I have the following regex for searching, I'm not sure if it's proper :

\?[0-9]+

But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.

2
  • 1
    Is there a specific reason to use a regex? You could use the location object, respectively location.search. Commented Jul 8, 2011 at 15:00
  • Your regex is a-ok. You just need to add back in the ? you take out. See my answer below. Commented Jul 8, 2011 at 16:44

5 Answers 5

3

Try this:

var url = "http://website.com/avatars/avatar.png?56"; 
var match = url.match(/\?(\d+)/); 
if(match != null) {
   url = url.replace(match[1], "new number");
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, no, matches[1] will be "56", and the replace statement is effectively: url = url.replace('56', "new number"); and the URL value ends up being: website.com/pathnew number/avatar.png?56.
1

Your original regex will work just fine, just add back in the ? you are taking out like so:

var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);

Comments

0

I'm no regex expert but I think you can use a lookaround to ignore the '?'

(?<=?)([0-9]+)

which should give you your number in the first match

2 Comments

this is very simple,you can split the matched values using the () there an example in above my post...
Javascript does not have lookbehind.
0

VERY dummied-down approach:

$('#parse').click(function(e){
    var fromUrl = $('#from-url').val();
    var newNum = parseInt($('#new-number').val(), 10);

    var urlRE = /(?!\?)(\d+)$/;
    if (urlRE.test(fromUrl)){
        $('#result').text(fromUrl.replace(urlRE, newNum));
    }else{
        $('#result').text('Invalid URL');
    }
});

DEMO

There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.


Broken out in to a function (demo):

// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
    // regex to find (and replace) the numbers at the end.
    var urlRE = /\?\d+$/;

    // make sure the url end in a question mark (?) and
    // any number of digits
    if (urlRE.test(url)){
        // replace the ?<number> with ?<newNumber>
        return url.replace(urlRE, '?'+newNumber);
    }

    // invalid URL (per regex) just return same result
    return url;
}

alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));

3 Comments

The expression /(?!\?)(\d+)$/ is equivalent to /(\d+)$/ (The negative lookahead assertion will always be true at the position of a digit!)
@ridgerunner: They wanted to confirm that the link ended with a question mark and numbers. The negative look-ahead validates that. (Unless I'm misunderstanding what you're stating)
No, the negative lookahead does no such thing. It is a zero width assertion applied immediately preceding the first digit - it does not verify that the character before the first digit is a question mark. Remember that lookahead and lookbehind assertions are applied between characters, In this case, between the question mark (if its actually there), and the first digit.
0

You could do this without regex.

var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
  1. Split the URL at the ?
  2. This returns an array.
  3. Add the first item in the array and the ? and the new number back together.

http://jsfiddle.net/jasongennaro/7dMur/

2 Comments

What if there is more than one ? character? (The ? is valid in both ?query and #fragment.) Also, what if there are more query parameters (or a #fragment) following the number?
Thx @ridgerunner. I didn't consider any of those scenarios because the OP said check if it has a ? followed by number with varying amount of digits and his example was http://website.com/avatars/avatar.png?56 I figured it was pretty clear cut. But agreed, a more complex URL would require something else.

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.