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?
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
You only need to use the new RegExp()
part when creating dynamic regular expressions. You can use literals at other times. /\d+/ is the equivalent of new RegExp("\\d+")
. Note that you have to escape special characters when using the latter.
Also noteworthy is that String#match
returns null or an array. This is not apparent based on the supplied solutions (parseInt(name.match(/\d+/), 10)
). It just so happens that it is converted to a string when passed to parseInt
. ParseInt converts string values to integers (when possible).
name.match(/\d+/)[0]
/\d+/.exec(name)[0]
Those two are functionally identical in this case.
The other match you were referring to (the negative matching) requires a special flag. To duplicate the functionality of gsub you need to tell the regex to be applied more than once with the g
flag.
'users[107][teacher_type]'.replace(/users\[|\]\[teacher_type\]/g,'')
Or if you had to use new RegExp
for some reason you'd accomplish the same as above like so:
'users[107][teacher_type]'.replace(new RegExp('users\[|\]\[teacher_type\]', 'g'),'')
Notice again how I had to escape all the backslashes. Mozilla's Developer Center is a good reference to familiarize yourself with regex in javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With