I want to test if a string can match a pattern in javascript
problem is there is a random string in the middle pattern: "account/os/some_random_string/call_back"
so a string look like below will match
var mystring = "account/os/1234567/call_back"
thanks
You want a regex for starts with account/os/
and ends with /call_back
, here's one:
/^account\/os\/.*\/call_back$/
.*
will match any random string (including the empty string.). If you want a minimum length on the random string you change the *
:
.* : 0 or more characters
.+ : 1 or more characters
.{n,} : n or more characters (replace n with an actual number)
Well, it depends. If you want every single character between account/os/ and /call_back, use this:
var randomStr = mystring.match(/account\/os\/(.*)\/call_back/)[1];
The match will return an array with 2 elements, the first one with the entire match, the 2nd one with the group (.*). If you are completely sure that you have at least one character there, replace * with +.
If you know something more specific about the text you have to collect, here are some replacements for the .(dot is matching almost everything):
[A-z] for any of A, B, .. , Y, Z, a, b, .. , y, z
[0-9] for any digit
You can mix then and go fancy, like this:
[A-Ea-e0-36-8]
So, your pattern may look like this one:
/account\/os\/([A-Ea-e0-36-8]*)\/call_back/
Your example have a number there, so you are probably looking for:
/account\/os\/([0-9]*)\/call_back/
or
/account\/os\/(\d*)\/call_back/
.. it's the same thing.
Hope that helps.
Edit: What JS answer doesn't have a jsfiddle? http://jsfiddle.net/U2Jhw/
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