1

I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.

I tried this but it is not working

https://www.google.com/55.html
    url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
                    return((Number(p1) + 1) + p2);

Please I need help but not with jQuery because it does not make a lot of sense to me.

3
  • If you're trying to get a number, why are you calling replace? Commented Jan 21, 2012 at 22:37
  • Are you saying the number you want to retrieve will always be between the last / and .html? And you'll never have something like www.something.com/test55.html? Commented Jan 22, 2012 at 1:05
  • it is always a number, and only a number Commented Jan 22, 2012 at 2:00

3 Answers 3

1
var numPortion = url.match(/(\d+)\.html/)[1]

(Assumes a match; if it might not match, check the results before applying the array subscript.)

Sign up to request clarification or add additional context in comments.

2 Comments

@JoeTuskan I don't know what you're talking about.
Nice, I usually don't get to chuckle on SO!
0

Try this

var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);

match is an array, match[0] contains the matched expression from your script, match[1] is the number (the 1st parenthesis), and so on

6 Comments

I tried this :var a = location.href; var match = a.match(/(\d+)(\.html)/); <img src="Images/' +match+ '.jpg"> still it is not working
Perhaps I didn't give my array a good name. Try this: <img src="Images/' +match[1] + '.jpg">
does it matter if it is a string or a digit ?
no, but the 1st group of () is looking for a number, so in match[1] you'll have something that looks like a number. If the url is not of this format (<number>.html), than the regular expression doesn't match and aout array, match, will be null.
Now I have this <script>var a = location.href; var match = a.match(/(\d+)(\.html)/); </script> <img src="Images/' +match[1] + '.jpg"> but I do not know why it is not working ?
|
0
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1];  // <-- shortcut for using if else

Comments

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.