I want to print the number from the middle of the string in JavaScript . In Ruby (my main language) I would do the following:
Ruby:
name = "users[107][teacher_type]" num = name.scan(/\d+/).first
But in JavaScript, I have to do this, which seems a bit awkward.
JavaScript:
var name = "users[107][teacher_type]" var regexp = new RegExp(/\d+/) var num = regexp.exec(name)[0]
Is there a way to pull the relevant parts without creating a RegExp object? That is, the one-line equivalent of a Ruby String # scan string?
Also, as a side note, since this line will always have the same format, I could do this with .replace. This is not such a smart solution, but again I have problems with JavaScript.
In Ruby:
num = name.gsub(/users\[|\]\[teacher_type\]/,"")
But when I try this in JavaScript, I don't like it or (|) in the middle of the regular expression:
In JavaScript:
//works num = name.replace(/users\[/, "").replace(/\]\[teacher_type\]/,"") //doesn't work num = name.gsub(/users\[|\]\[teacher_type\]/,"")
Can anyone set me straight?
javascript regex
Max williams
source share