Reputation: 321
I am new to regular expressions in Javascript.
The string looks something like
Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney
and I am trying to extract from this just the bit
Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517
from ths string.
So, I have:
string="`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
substring=string.match('/Password=(.*);/g');
It returns back the entire string again. What is going wrong here?
Upvotes: 6
Views: 21368
Reputation: 3367
Avoid using potential reserved words.
Your first regular expression worked, you just added useless quote around it. Removig it will works.
var myString = "`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
var mySubstring = myString.match(/Password=(.*);Persist /g); // Remove the ' around the regex
var thePassword = mySubstring[0].replace('Password=', '');
thePassword = thePassword.replace(';Persist ', '');
Upvotes: 0
Reputation: 39027
It's useful to think of the underlying grammar / syntax:
string := 'Password=' password ';' ...
So you want to match the non-semicolon characters.
string="`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney"
/Password=([^;]+)/.exec(string)[0] // or [1] if you want just the password
Upvotes: 2
Reputation: 513
You could Simply try this /Password.*;/
So you start looking for a String with Password
in the beginning, followed by whatever character, until you reach a ;
.
By using the g
at the end of your RegEx, you are setting it for global, so you are not only looking for the first ;
, but for every one. This might have been the reason why yours did not work.
Upvotes: 0
Reputation: 87203
Regex should not be wrapped in quotes. Use [^;]+
to select anything until ;
.
var password = string.match(/Password=([^;]+)/)[1];
string = "`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney";
var password = string.match(/Password=([^;]+)/)[1];
document.write(password);
Or lazy regex can also be used
/Password=(.*?);/g
^
var string = "`Password=6)8+Ea:4n+DMtJc:W+*0>(-Y517;Persist Security Info=False;User ID=AppleTurnover;Initial Catalog=ProductDB;Data Source=Sydney";
var password = string.match(/Password=(.*?);/g);
document.write(password);
Upvotes: 22