Regex - get numbers after a certain character string

I have a text string, which can be any number of characters that I would like to add at the end of the order number. Then I can pull out the order number when I need to use it again. Since there is a possibility that the number is of variable length, I would like to make a regular expression that will catch everything after the = sign in the string ?order_num=

So the whole line will be

 "aijfoi aodsifj adofija afdoiajd?order_num=3216545" 

I tried using the regex generator online, but no luck. Can someone please help me with extracting the number at the end and putting them in a variable and something that puts what comes before ?order_num=203823 in its own variable.

I will send my own attempts, but I foresee failure and confusion.

+8
javascript regex
source share
3 answers
 var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545"; var m = s.match(/([^\?]*)\?order_num=(\d*)/); var num = m[2], rest = m[1]; 

But remember that regular expressions are slow. Use indexOf and substring / slice when you can. For example:

 var p = s.indexOf("?"); var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p); 
+18
source share

I don't see the need for a regex for this:

 var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545"; var n=str.split("?"); 

n will then be an array where index 0 is before the character? and index 1 after.

Another example:

 var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545"; var n=str.split("?order_num="); 

You will get the result: n[0] = aijfoi aodsifj adofija afdoiajd and n[1] = 3216545

+9
source share

Can you fine-tune from the first instance ? forward and then a regular expression to get rid of most of the difficulties in expression and improve performance (which is probably negligible at all, and nothing to worry about if you don't do it for more than a thousand iterations). in addition, it will correspond to order_num= at any point in the query string, and not just at the very end of the query.

 var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/); if (match) { alert(match[1]); } 
+2
source share

All Articles