Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - regex - get numbers after certain character string

I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=

So the whole string would be

"aijfoi aodsifj adofija afdoiajd?order_num=3216545"

I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.

I'll post some attempts of my own, but I foresee failure and confusion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...