3

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?

4 Answers 4

2

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..)

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

1 Comment

You shouldn't split with regex in <=IE8
2
var str = "item4",
    num = (str.match(/item([0-9]+)/)||[])[1]; // if no match, `match` will return null therefore the `|| []` (or empty array). 

console.log(num); // "4" (typeof num === "string")

console.log(+num) // 4 (typeof num === "number")

Comments

1

You can use match like this:

var str = "item4",
    num = +str.match(/item(\d+)/)[1]; // => 4

I used unary + to cast to a number. You can use parseInt or Number constructor instead.

Comments

0

You need to use .match(..) with a capture group.

"floatLeft item4".match(/item(\d+)/)
// Result: ["item4", "4"]

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.