I want to pull a number out the middle of a string in JavaScript. In Ruby (my main language) I would do this:
Ruby:
name = "users[107][teacher_type]"
num = name.scan(/\d+/).first
But in JavaScript I have to do this, which seems a bit clunky.
JavaScript:
var name = "users[107][teacher_type]"
var regexp = new RegExp(/\d+/)
var num = regexp.exec(name)[0]
Is there way to pull out the matching parts without building a RegExp object? I.e. a one-liner equivalent of Ruby's String#scan?
Also, as a side note, since this string will always have the same format, I could potentially do it using .replace. This isn't as clever a solution but again I have problems in JavaScript.
In Ruby:
num = name.gsub(/users\[|\]\[teacher_type\]/,"")
But when I try this in JavaScript it doesn't like the or (|) in the middle of the regex:
In JavaScript:
//works
num = name.replace(/users\[/, "").replace(/\]\[teacher_type\]/,"")
//doesn't work
num = name.gsub(/users\[|\]\[teacher_type\]/,"")
Can anyone set me straight?