Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex get the number part from a specific word

Say that we have an element with these classes: "floatLeft item4".

If I want to save the number "4" to a variable from "item4" how would i do that?

I think I would use this pattern "/item(\d+)/" but do I use replace or match and how?

like image 805
halliewuud Avatar asked Apr 24 '26 02:04

halliewuud


1 Answers

using replace:

"floatLeft item4".replace(/.*item(\d+)/,"$1")

using match:

"floatLeft item4".match(/item(\d+)/)[1]

exec (alot like match)

/item(\d+)/.exec("floatLeft item4")[1]

using split (again, alot like match):

"floatLeft item4".split(/item(\d+)/)[1]

http://jsfiddle.net/UQBNn/

though the split method is not supported in all browsers (like IE..)

like image 197
user2153497 Avatar answered Apr 26 '26 15:04

user2153497